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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Containers Trend Report: Explore the current state of containers, containerization strategies, and modernizing architecture.

Low-Code Development: Learn the concepts of low code, features + use cases for professional devs, and the low-code implementation process.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

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

  • The Top 5 Tools for Automated Front-End Testing
  • Software Architecture Design Patterns for Serverless System
  • Harnessing the Power of APIs: Shaping Product Roadmaps and Elevating User Experiences through Authentication
  • Data Privacy and Security
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring - Accessing injected properties from constructor

Spring - Accessing injected properties from constructor

Fahim Farook user avatar by
Fahim Farook
·
Nov. 23, 14 · Interview
Like (2)
Save
Tweet
Share
19.6K 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

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: