当前位置: 首页 > 面试题库 >

带有注释的Bean定义继承?

巫马心水
2023-03-14
问题内容

使用基于注释的配置(@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 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在需要时插入其他位置。



 类似资料:
  • 问题内容: 使用基于注释的配置(等)是否可以实现相同的bean继承? http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/spring-framework- reference/htmlsingle/#beans-child-bean- definitions 问题答案: java config中没有抽象bean的概念,因为Java语言已经

  • 我已经用自定义注释注释了Spring bean,但似乎Spring在创建bean后删除了我的自定义注释。 第二步不行,我的自定义注释丢失了。(可能是到期的代理文件) 我的豆子 我的一个自定义注释的示例 findAndDoStuffWithAnnotatedThings Bean中出错的内容被传递到一个类,在该类中,我的自定义注释得到验证,但我的验证程序找不到任何注释。(Util使用isAnnota

  • 我有这个spring配置: 如何获取用Foo注释的所有bean的列表? 注意:

  • 如何使用注释在Spring中提供bean继承?在XML配置中,我使用了

  • 我目前正在开发一个尽可能尊重六边形架构原则的应用程序。 因此,我的“域”模块(组Id: ; 工件Id:)不依赖于任何技术框架。 我的所有服务都使用自定义注释(本身是我域的一部分)进行注释: 然而,在我的“Quarkus应用”模块(groupId:< code > acme ;artifact id:< code > app-quar kus ,我需要注入我的“域”模块中定义的服务(< code>a

  • 我有一些这样的豆子: 3)移动将在bins中搜索注释移动到,并将setter添加到: 但是在这个解决方案中,我不喜欢方法。