有没有办法使用<bean parent="someParent">@Component注释(使用注释创建spring bean)?
我想使用@Component注释创建具有"spring parent"的spring bean.
可能吗?
根据我的评论,这条XML
<bean id="base" abstract="true">
<property name="foo" ref="bar"/>
</bean>
<bean class="Wallace" parent="base"/>
<bean class="Gromit" parent="base"/>
Run Code Online (Sandbox Code Playgroud)
或多或少与此代码等效(注意我创建了人工Base类,因为Spring中的抽象bean不需要class):
public abstract class Base {
@Autowired
protected Foo foo;
}
@Component
public class Wallace extends Base {}
@Component
public class Gromit extends Base {}
Run Code Online (Sandbox Code Playgroud)
Wallace而Gromit现在有机会获得共同Foo财产.你也可以覆盖它,例如在@PostConstruct.
BTW我真的很喜欢parentXML中的功能,它允许保持bean DRY,但Java方法看起来更清晰.