带定义的Bean定义继承? [英] Bean definition inheritance with annotations?

查看:94
本文介绍了带定义的Bean定义继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<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配置中的抽象bean,因为java语言已经拥有了你需要的一切。不要忘记抽象bean根本没有暴露在上下文中,它是某种模板。

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

如果 initTestBean 应该是共享的,您也可以将其公开,如果需要,可以在其他地方注入 Config

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

这篇关于带定义的Bean定义继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆