【问题标题】:Bean definition inheritance with annotations?带有注释的Bean定义继承?
【发布时间】:2023-03-10 07:55:01
【问题描述】:

是否可以使用基于注解的配置(@Bean 等)实现相同的 bean 继承?

<bean id="inheritedTestBean" abstract="true"
        class="org.springframework.beans.TestBean">
    <property name="name" value="parent"/>
    <property name="age" value="1"/>
</bean>

<bean id="inheritsWithDifferentClass"
        class="org.springframework.beans.DerivedTestBean"
        parent="inheritedTestBean" init-method="initialize">
    <property name="name" value="override"/>
    <!-- the age property value of 1 will be inherited from parent -->
</bean>

http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#beans-child-bean-definitions

【问题讨论】:

    标签: java spring


    【解决方案1】:

    java config 中没有抽象 bean 的概念,因为 java 语言已经拥有你需要的一切。不要忘记抽象 bean 根本没有暴露在上下文中,它是某种模板。

    您可以将上面的代码改写如下:

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

    如果initTestBean应该被共享,你也可以将其公开,如果需要,将Config注入其他地方。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多