我试图理解在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>


 是@Configuration,是@ComponentScan。

如果可以说我用@Component声明了所有的bean(首先忽略了@ Repository,@ Service等更具体的bean)注释,并确保通过@ComponentScan注释对软件包进行扫描,那么在什么情况下我会出现特殊情况?仍会同时使用@Configuration和@ComponentScan来注释我的课程?

我问这个问题是因为有时我会同时看到同时用@Configuration和@ComponentScan注释的类。

最佳答案

首先请仔细阅读以下内容:

Difference between <context:annotation-config> vs <context:component-scan>

因此,<context:component-scan>进行扫描作业,并且与<context:annotation-config>进行相同的作业,这意味着可以使用DI批注来解决。

然后,请考虑:


<context:component-scan>等同于@ComponentScan
<context:annotation-config>没有等效的注释。



  什么是特殊的用例,在这里我仍会注释我的班级
  @Configuration和@ComponentScan一起使用?


@Configuration用于定义有关基础结构的bean,例如DatabaseJMS等。

是的,一个类可以同时使用,例如,可以用于MVC Infrastructure @Configuration,例如:

@EnableWebMvc
@Configuration
@ComponentScan("com.manuel.jordan.controller", "com.manuel.jordan.rest")
public class WebMvcConfig extends WebMvcConfigurerAdapter {


因此,从该类中,您正在配置MVC,并且仅指示扫描“ Web端”所创建的MVC类,例如:@Controller@RestController

关于java - 在Spring中将@Configuration与@ComponentScan一起使用的特定用例是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46654307/

10-10 01:06