difference between @Component and @Configuration in Spring 3

后端 未结 5 1865
悲哀的现实
悲哀的现实 2020-12-02 21:48

I came across two annotations provided by Spring 3 (@Component and @Configuration) I am a bit confused between these.
Here is what I read about @Component

5条回答
  •  孤街浪徒
    2020-12-02 21:52

    Although this is old, but elaborating on JavaBoy And Vijay's answers, with an example:

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

提交回复
热议问题