I have requirement to inject dependency in abstract superclass using spring framework.
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)
entry in application.xml (spring context file)
<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?
Third, as Spring doesn't support constructor injection in an abstract class, we should generally let the concrete subclasses provide the constructor arguments. This means that we need to rely on constructor injection in concrete subclasses.
By using an abstract class as the dependency-injection token in conjunction with the useClass @Injectable() option, we're able to keep the simplicity of the providedIn syntax while also allowing for the traditional override functionality of Providers. It's the best of both worlds!
An abstract class can have constructors like the regular class. And, we can access the constructor of an abstract class from the subclass using the super keyword.
Specifically, we saw that placing the @Service annotation on interfaces or abstract classes has no effect and that only concrete classes will be picked up by component scanning when they're annotated with @Service. As always, all the code samples and more are available over on GitHub.
You can create an abstract bean definition, and then "subtype" that definition, e.g.
<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 b
doesn't even require you to specify the class, you can leave that out:
<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 Manual discusses bean definition inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With