Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

java - Bean definition inheritance with annotations?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...