DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Visually Designing Views for Java Web Apps
  • How to Activate New User Accounts by Email
  • How To Read the Properties File Outside the Jar in Spring Boot

Trending

  • Beyond Conversation: Mastering Context with Claude Code Skills and Agents
  • Spring Boot Done Right: Lessons From a 400-Module Codebase
  • Comparing Top Gen AI Frameworks for Java in 2026
  • Bringing Intelligence Closer to the Source: Why Real-Time Processing is the Heart of Edge AI
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring - Accessing injected properties from constructor

Spring - Accessing injected properties from constructor

By 
Fahim Farook user avatar
Fahim Farook
·
Nov. 23, 14 · Interview
Likes (2)
Comment
Save
Tweet
Share
20.9K Views

Join the DZone community and get the full member experience.

Join For Free

In Spring, a bean is instantiated before its properties are injected. That is:

  1. Instantiate the bean first
  2. 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.

Spring Framework Property (programming)

Published at DZone with permission of Fahim Farook. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Visually Designing Views for Java Web Apps
  • How to Activate New User Accounts by Email
  • How To Read the Properties File Outside the Jar in Spring Boot

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook