difference between @Component and @Configuration in Spring 3

后端 未结 5 1821
悲哀的现实
悲哀的现实 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 22:01

    Here is difference with full example :-

    //@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) Here if Config class annotated with @configuration , than a() method and b() method , both will be called once .

    2)Here if Config class annotated with @component , than b() method will be called once but a() method will be called twice .

    Problem in (2) :- since we have noticed the problem with @component annotation . This second configuration (2) is totally incorrect because spring will create a singleton bean of A, but B will obtain another instance of A which is out of the spring context control.

    Solution :- we can use @autowired annotation with @component annotation inside Config class .

    @Component
    public static class Config {
        @Autowired
        A a;
    
        @Bean
        public A a() {
            return new A();
        }
    
        @Bean
        public B b() {
            return new B(a);
        }
    }
    

提交回复
热议问题