在抽象超类中注入 spring 依赖
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4238987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inject spring dependency in abstract super class
提问by bob
I have requirement to inject dependency in abstract superclass using spring framework.
我需要使用 spring 框架在抽象超类中注入依赖项。
class A extends AbstractClassB{
private Xdao daox ;
...
public setXdao() { ... }
}
class AbstractClassB{
..
private yDao daoy;
public seyYdao() { ... }
}
I need to pass superclass dependency everytime i instantiate Abstract class B (which can be subclassed in 100's of ways in my project)
每次实例化抽象类 B 时,我都需要传递超类依赖项(可以在我的项目中以 100 种方式进行子类化)
entry in application.xml (spring context file)
application.xml 中的条目(spring 上下文文件)
<bean id="aClass" class="com.mypro.A"
<property name="daox" ref="SomeXDaoClassRef" />
<property name="daoy" ref="SomeYDaoClassRef"/>
</bean>
How can i just create bean reference of super class AbstractClassB in application.xml so that i can use it in all subclass bean creation?
我怎样才能在 application.xml 中创建超类 AbstractClassB 的 bean 引用,以便我可以在所有子类 bean 创建中使用它?
回答by skaffman
You can create an abstract bean definition, and then "subtype" that definition, e.g.
您可以创建一个抽象 bean 定义,然后对该定义进行“子类型化”,例如
<bean id="b" abstract="true" class="com.mypro.AbstractClassB">
<property name="daox" ref="SomeXDaoClassRef" />
</bean>
<bean id="a" parent="b" class="com.mypro.A">
<property name="daoy" ref="SomeYDaoClassRef" />
</bean>
Strictly speaking, the definition for bdoesn't even require you to specify the class, you can leave that out:
严格来说, for 的定义b甚至不需要您指定类,您可以将其省略:
<bean id="b" abstract="true">
<property name="daox" ref="SomeXDaoClassRef" />
</bean>
<bean id="a" parent="b" class="com.mypro.A">
<property name="daoy" ref="SomeYDaoClassRef" />
</bean>
However, for clarity, and to give your tools a better chance of helping you out, it's often best to leave it in.
但是,为了清楚起见,并让您的工具有更好的机会帮助您,通常最好将其保留。
Section 3.7 of the Spring Manualdiscusses bean definition inheritance.
Spring 手册的第 3.7 节讨论了 bean 定义继承。
回答by peakit
You can use the abstractflag of Spring to tell Spring that a class is abstract. Then all concrete implementations can simply mark this bean as their parentbean.
您可以使用Spring的抽象标志告诉 Spring 一个类是抽象的。然后所有具体的实现都可以简单地将此 bean 标记为它们的父bean。
<bean id="abstractClassB" class="AbstractClassB" abstract="true">
<property name="yDao" ref="yDao" />
</bean>
<bean id="classA" class="A" parent="abstractClassB">
<property name="xDao" ref="xDao" />
</bean>

