Bean definition of 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

+5
java spring
source share
1 answer

There is no concept of an abstract bean in java config, because the java language already has everything you need. Do not forget that abstract beans do not appear in context at all, this is a kind of template.

You can rewrite your code 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 value of initTestBean to be shared, you can make it public and enter Config elsewhere if you need to.

+9
source share

All Articles