Spring 3中@Component和@Configuration之间的区别

Ana*_*and 14 java spring spring-3

我遇到了Spring 3提供的两个注释(@Component@Configuration)我对它们感到有些困惑.
这是我读到的关于@Component的内容

把这个"context:component"放在bean配置文件中,就意味着,在Spring中启用自动扫描功能.base-package指示存储组件的位置,Spring将扫描此文件夹并找出bean(使用@Component注释)并将其注册到Spring容器中.

所以我想知道@Configuration的用途是什么,如果@Controller将注册我的bean而不需要在spring配置xml文件中声明它们

Jav*_*boy 16

来自Book Pro Spring Integration

@Configuration类与常规@Components类一样,除了注释的方法@Bean用于工厂bean.注意@Component带有@Bean注释方法的a 以相同的方式工作,除了不考虑范围并@Bean重新调用方法(没有缓存),所以@Configuration是首选,即使它需要CGLIB

  • "请注意,A与B类似,只是B的行为与X相同.请注意,A的行为与X相似." 大. (11认同)

Ric*_*win 9

@Configuration 是Spring 3中引入的基于Java的配置机制的核心.它提供了基于XML的配置的替代方案.

所以下面的两个片段是相同的:

<beans ...>
    <context:component-scan base-package="my.base.package"/>
    ... other configuration ...
</beans>
Run Code Online (Sandbox Code Playgroud)

和:

@Configuration
@ComponentScan(basePackages = "my.base.package")
public class RootConfig {
    ... other configuration ...
}
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,Spring将扫描my.base.package及以下带注释的类@Component或者是元注释与其他注释的一个@Component@Service.


Vij*_*pta 9

这是与完整示例的区别:

//@Configuration or @Component
public static class Config {
    @Bean
    public A a() {
        return new A();
    }
    //**please see a() method called inside b() method**
    @Bean
    public B b() {
        return new B(a());
    }
}
Run Code Online (Sandbox Code Playgroud)

1)如果在Config类中使用@configuration注释,则a()方法和b()方法都将被调用一次

2)如果使用@component注释的Config类,则b()方法将被调用一次,而a()方法将被调用两次

(2)中的问题:-因为我们已经注意到@component注解的问题。第二种配置(2)完全不正确,因为spring将创建A的单例bean,但是B将获得spring上下文控件之外的A的另一个实例。

解决方案:-我们可以在Config类中将@autowired注释与@component注释一起使用。

@Component
public static class Config {
    @Autowired
    A a;

    @Bean
    public A a() {
        return new A();
    }

    @Bean
    public B b() {
        return new B(a);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为b将在(2 (6认同)