gpt4 book ai didi

java - @Component 与父级?

转载 作者:IT老高 更新时间:2023-10-28 13:47:18 25 4
gpt4 key购买 nike

有什么方法可以使用<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"/>

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

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 方法似乎更干净。

关于java - @Component 与父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8270320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com