Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring and Abstract class - injecting properties in abstract classes

Tags:

java

spring

I have an abstract base class with a property called "mailserver" which I wish to inject from the spring ioc container. However when I run the concreted implementations of the abstract class I get a null for the mailserver property.

What is the correct way of doing this? Have you tried doing someting like this and been successful? Please share.

like image 670
Khushroo Mistry Avatar asked Aug 25 '11 02:08

Khushroo Mistry


People also ask

Can I inject an abstract class in 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 create properties in abstract class?

An abstract class cannot be instantiated. An abstract class not only contains abstract methods and assessors but also contains non-abstract methods, properties, and indexers.

Can we create Bean of abstract class in spring?

You don't. You only declare the beans which have a concrete subclass of that abstract class.

How do you inject spring boot properties?

Injecting Properties Using @ValueUsing the @Value annotation, we can inject the values from the application. properties file into class fields in the Spring-managed bean GreetController . Using @Value allows you to set a default value if the requested one, for any reason, isn't available: @Value("${message.


2 Answers

Mark the abstract base class definition as abstract by using the abstract attribute , and in the concrete class definition , make the parent attribute be the name of the abstract class 's bean name

Something like this:

<bean id="abstractBaseClass" abstract="true" class="pacakge1.AbstractBaseClass">
  <property name="mailserver" value="DefaultMailServer"/>
</bean>

<bean id="concreteClass1" class="pacakge1.ConcreteClass1" parent="abstractBaseClass">     
  <!--Override the value of the abstract based class if necessary-->
  <property name="mailserver" value="AnotherMailServer"/>
</bean>
like image 60
Ken Chan Avatar answered Oct 19 '22 23:10

Ken Chan


Properties in superclasses, abstract or not, are injected exactly the same as any other properties in Spring. You can use setter, constructor, or field injection based on XML, annotations, or Java config. You'll find extensive use of inheritance all across Spring: the DefaultMessageListenerContainer, for example. Show how you're trying to wire the property, and someone can give you an explanation of why it's not working.

like image 20
Ryan Stewart Avatar answered Oct 19 '22 23:10

Ryan Stewart