Java 在Spring中使用@Configuration和@ComponentScan的具体用例是什么?
我试图理解Spring中从使用xml注释到基于java注释的转换。我有这些定义Java 在Spring中使用@Configuration和@ComponentScan的具体用例是什么?,java,spring,annotations,Java,Spring,Annotations,我试图理解Spring中从使用xml注释到基于java注释的转换。我有这些定义 <context:annotation-config>: Scanning and activating annotations for already registered beans in spring config xml. <context:component-scan>: Bean registration + <context:annotation-config>
<context:annotation-config>: Scanning and activating annotations for already registered beans in spring config xml.
<context:component-scan>: Bean registration + <context:annotation-config>
:扫描并激活spring配置xml中已注册bean的注释。
:Bean注册+
是@Configuration,是@ComponentScan
如果让我们假设我用@Component(先不考虑@Repository、@Service等更具体的bean)注释声明我的所有bean,并确保包被@ComponentScan注释扫描,那么我仍然用@Configuration和@ComponentScan注释我的类的特殊用例是什么
我问这个问题是因为有时我看到同时用@Configuration和@ComponentScan注释的类 这取决于你的喜好和编码风格。文件规定: 可以指定basePackageClasses()或basePackages()(或其别名值())来定义要扫描的特定包。如果未定义特定的包,将从声明此注释的类的包中进行扫描
因此,每次您看到的只是
@ComponentScan
注释,这意味着应该扫描所有子包。对于每个功能布局的软件包,这是一种合理的方法:当您的功能有一个@配置
类时,以及与子软件包中的功能相关的所有@组件
。首先仔细阅读以下内容:
因此,
执行扫描作业并且与
执行的作业相同,这意味着使用DI
注释
那么现在考虑一下:
相当于@ComponentScan
注释没有等效项
@Configuration
用于定义有关数据库结构的bean,如数据库
,JMS
等
是的,一个类可以同时使用这两者,例如,它可以用于MVC基础设施@配置
,例如:
@EnableWebMvc
@Configuration
@ComponentScan("com.manuel.jordan.controller", "com.manuel.jordan.rest")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
因此,从该类中,您正在配置MVC,并指示仅扫描您为“web端”创建的MVC类,例如:@Controller
,@RestController
没有用于注释的等价物。这一点很有帮助,我一直认为@Configuration是java注释的等价物