2012-08-10 48 views
10

我遇到了Spring 3提供的两个注解(@Component@Configuration) 我在这些之间有点混淆。
这是我读到@Component@Component和@Configuration在Spring 3中的区别

将这个“背景:组件”在bean配置文件,这意味着, 启用春季自动扫描功能。基本包指示 你的组件存储在哪里,Spring会扫描这个文件夹并且 找出bean(用@Component注解),并在 Spring容器中注册它。

所以我想知道有什么用@Configuration的那么如果@Controller将注册我的豆子,而不需要他们宣告春天配置XML文件

回答

8

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

所以2个以下片段是相同的:

<beans ...> 
    <context:component-scan base-package="my.base.package"/> 
    ... other configuration ... 
</beans> 

和:

@Configuration 
@ComponentScan(basePackages = "my.base.package") 
public class RootConfig { 
    ... other configuration ... 
} 

在两种情况下Spring将在my.base.package和下方扫描与@Component或其他注释的一个注解的类其用@Component进行元注释,例如@Service

7

从书临春集成

@Configuration类就像普通@Components类,除了具有@Bean注解的方法被用于工厂bean。请注意,@Bean注释的方法@Component的工作方式相同,只是范围不被尊重和@Bean方法是重新调用(在戏没有缓存),所以@Configuration是首选,尽管它需要CGLIB

+6

“注意,是样B除了是b的行为像X.注意,也表现得像X。”大。 – 2016-01-11 11:52:08

0

这里与完整的例子的区别: -

//@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()); 
    } 
} 

1)在此,如果配置类注解为@Configuration,比()方法和b()方法,两者都将被称为一次

2)在此,如果用@Component注释的配置类,比()方法将被调用一次 B()方法将被调用两次

问题在(2): - 因为我们已经注意到了@compenent注解的问题。 这个第二个配置(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); 
    } 
} 
+1

我想b会被称为一次和两次(2 – 2017-09-03 13:36:07

0

虽然这是旧的,但详细阐述JavaBoy和维杰的答案,用一个例子:

@Configuration 
public class JavaConfig { 
    @Bean 
    public A getA() { 
     return new A(); 
    } 
} 

@Component 
@ComponentScan(basePackages="spring.example") 
public class Main() { 
    @Bean 
    public B getB() { 
     return new B(); 
    } 
    @Autowired 
    JavaConfig config; 

    public static void main(String[]a) { 
     Main m = new AnnotationConfigApplicationContext(Main.class) 
      .getBean(Main.class); 
     /* Different bean returned everytime on calling Main.getB() */ 
     System.out.println(m.getB()); 
     System.out.println(m.getB()); 
     /* Same bean returned everytime on calling JavaConfig.getA() */ 
     System.out.println(m.config.getA()); 
     System.out.println(m.config.getA()); 
    } 
} 
相关问题