Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject spring dependency in abstract super class

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?

like image 221
bob Avatar asked Nov 21 '10 16:11

bob


People also ask

Can abstract class inject spring?

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.

Can we use abstract class for dependency injection?

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!

Can we use super in abstract class?

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.

Can abstract class have service annotation?

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.


1 Answers

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.

like image 167
skaffman Avatar answered Oct 07 '22 09:10

skaffman