Spring - Accessing injected properties from constructor
Join the DZone community and get the full member experience.
Join For FreeIn Spring, a bean is instantiated before its properties are injected. That is:
- Instantiate the bean first
- Inject the properties
This is because spring uses setter methods of the instantiated bean in order to inject properties. (This is true if the property injection is declared in the spring configuration file, however if the bean properties are auto-wired - no setter methods are required. But still spring instantiates the bean first before auto-wiring properties.) Therefore you cannot access the properties from your constructor (unless properties are injected through constructor-args) as the properties are still holding null/ default values when accessed within the constructor.
Consider the following example.
Spring configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="engine" class="me.fahimfarook.sample.spring.Engine"> <property name="make" value="Toyota" /> <property name="cylinders" value="6" /> </bean> <bean id="car" name="car" class="me.fahimfarook.sample.spring.Car" > <property name="brand" value="Micro" /> <property name="year" value="2005" /> <property name="engine" ref="engine" /> </bean> </beans>
Engine.java
package me.fahimfarook.sample.spring; import java.util.logging.Logger; public class Engine { private String make; private int cylinders; private static Logger LOGGER = Logger.getLogger(Engine.class.getName()); public void cleanup() { LOGGER.info("Engine::cleanup - cleaning-up engine."); } public String getMake() { return make; } public void setMake(final String make) { this.make = make; } public int getCylinders() { return cylinders; } public void setCylinders(final int cylinders) { this.cylinders = cylinders; } }
Car.java
package me.fahimfarook.sample.spring; public class Car { private String brand; private int year; private Engine engine; public Car() { this.engine.cleanup(); } public String getBrand() { return brand; } public void setBrand(final String brand) { this.brand = brand; } public int getYear() { return year; } public void setYear(final int year) { this.year = year; } public Engine getEngine() { return engine; } public void setEngine(final Engine engine) { this.engine = engine; } }
As you can see I'm calling engine.start() from the constructor of the Car.
Main.java
package me.fahimfarook.sample.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { private static final String CONFIG_PATH = "classpath*:configs/spring/applicaton-config.xml"; public static void main(String[] args) { final ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG_PATH); final Car car = (Car)context.getBean("car"); } }
When you execute this main method you will get a NullPointerException.
Caused by: java.lang.NullPointerException at me.fahimfarook.sample.spring.Car.start(Car.java:18) at me.fahimfarook.sample.spring.Car.<init>(Car.java:14)
Even though we have configured spring to inject engine into car, by the time of instantiation (of car bean), spring has not injected the engine.
We have two workarounds to solve this problem.
1. From a design perspective this NullPointerException indicates a code smell. That is the relationship between the car and engine should be "composition" rather than "aggregation". The engine must cease to exist when car is destroyed. Also, the engine cannot exist without a car. In order to enforce composition between car and engine we need the following 2 changes.
- Add a constructor to Car with an Engine parameter
- Remove the setEngine() mutator
Here's the fixed code.
Spring config - Fixed
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="car" name="car" class="me.fahimfarook.sample.spring.Car" > <constructor-arg name="engine" ref="engine" /> <property name="brand" value="Micro" /> <property name="year" value="2005" /> </bean> <bean id="engine" class="me.fahimfarook.sample.spring.Engine"> <property name="make" value="Toyota" /> <property name="cylinders" value="6" /> </bean> </beans>
Note that engine is injected via a constructor-arg and <propertyname="engine"ref="engine"/> is removed.
Car.java - Fixed
package me.fahimfarook.sample.spring; public class Car { private String brand; private int year; private Engine engine; public Car(final Engine engine) { this.engine = engine; this.engine.start(); } public String getBrand() { return brand; } public void setBrand(final String brand) { this.brand = brand; } public int getYear() { return year; } public void setYear(final int year) { this.year = year; } public Engine getEngine() { return engine; } // public void setEngine(final Engine engine) { // this.engine = engine; // } }
Note that the setter of engine has been commented out and and Car is having a constructor with an Engine parameter. Now if you execute the main method you will not get the NullPointerException anymore as we have forced spring to inject an engine while construction of the car.
2. The other workaround would be to move the logic in the constructor to a separate method and annotate that method with @PostConstruct annotation. @PostConstruct is a standard Java annotation which is supported by spring. @PostConstruct indicates that the method annotated with @PostConstruct must be invoked once all its dependencies are injected only. However in our example you need to have <context:annotation-driven /> enabled in order to support annotations. You can find more information about this annotation here.
Published at DZone with permission of Fahim Farook. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments