Bean definition inheritance with annotations?

前端 未结 1 880
生来不讨喜
生来不讨喜 2020-12-10 13:30

Is it possible to achieve the same bean inheritance using annotation based configuration (@Bean etc)?



        
1条回答
  •  天涯浪人
    2020-12-10 13:49

    There is no notion of abstract bean in java config because the java language already has everything you need. Don't forget that abstract beans are not exposed in the context at all, it's some kind of template.

    You could rewrite your code above as follows:

    @Configuration
    public class Config {
    
        @Bean
        public DerivedTestBean() {
            DerivedTestBean bean = new DerivedTestBean();
            initTestBean(bean);
            bean.setName("override");
            return bean;
        }
    
        private void initTestBean(TestBean testBean) {
            testBean.setName("parent");
            testBean.setAge(1);
        } 
    }
    

    If the initTestBean should be shared, you can just as well make it public and inject Config in other places if you need to.

    0 讨论(0)
提交回复
热议问题