@Component与父母?

IAd*_*ter 11 java spring

有没有办法使用<bean parent="someParent">@Component注释(使用注释创建spring bean)?

我想使用@Component注释创建具有"spring parent"的spring bean.

可能吗?

Tom*_*icz 6

根据我的评论,这条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)

WallaceGromit现在有机会获得共同Foo财产.你也可以覆盖它,例如在@PostConstruct.

BTW我真的很喜欢parentXML中的功能,它允许保持bean DRY,但Java方法看起来更清晰.

  • 如果`base` bean将在XML中定义,无论是否创建人工`Bean`类,`wallace`和`Gromit`都将通过组件扫描创建,你的示例将无效. (5认同)