首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Component with parent?

@Component with parent?
EN

Stack Overflow用户
提问于 2011-11-25 22:12:39
回答 2查看 10.4K关注 0票数 11

有没有办法将<bean parent="someParent">与@Component注解结合使用(使用注解创建spring bean)?

我想使用@Component注解创建具有"spring parent“的spring bean。

有可能吗?

EN

回答 2

Stack Overflow用户

发布于 2011-11-25 23:03:30

在我的评论之后,这段XML

代码语言:javascript
复制
<bean id="base" abstract="true">
    <property name="foo" ref="bar"/>
</bean>

<bean class="Wallace" parent="base"/>
<bean class="Gromit" parent="base"/>

与这段代码或多或少是等价的(请注意,我创建了人工Base类,因为Spring中的抽象bean不需要class):

代码语言:javascript
复制
public abstract class Base {
    @Autowired
    protected Foo foo;
}

@Component
public class Wallace extends Base {}

@Component
public class Gromit extends Base {}

WallaceGromit现在可以访问公共Foo属性。您也可以覆盖它,例如在@PostConstruct中。

顺便说一句,我真的很喜欢XML中的parent特性,它可以让bean保持干燥,但是Java的方法看起来更干净。

票数 6
EN

Stack Overflow用户

发布于 2014-02-19 20:55:58

只是遇到了同样的结构..(一个通用的抽象父类,它将Beans with context.xml-声明用于组件扫描注入的潜在实现)

这是我可以在@Component类中做的事情:

代码语言:javascript
复制
@Autowired
public void setBeanUsedInParent(BeanUsedInParent bean) {
   super.setBeanUsedInParent(bean);
}

我最终做了..what (更好,因为它清楚地表明注入在对象上工作,而不是在类上)-如果你能够修改父类:

代码语言:javascript
复制
// abstract getter in parent Class
public abstract BeanUsedInParent getBeanUsedInParent();

..leave实际的Beans以及注入到实际实现的组件( @Component类):

代码语言:javascript
复制
@Autowired
private BeanUsedInParent beanUsedInParent;

@Override
public BeanUsedInParent getBeanUsedInParent() {
   return this.beanUsedInParent;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8270320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档