Awesome self improvement method

The pic below was taken this morning in the office toilet:

SAMSUNG

 

A clean code cheat sheet – loo list! I don’t know who’s got this idea, but it is AWESOME!

Way to go.

Advertisements

Spring dependency injection – @Configurable

Some time ago I was asked the question whether it is possible to inject dependencies into objects that are not created by Spring. Hmm, sweet. Let’s see if we can do it 🙂

In the EJB world, there is no way to inject dependencies into a bean created with the new operator – as I have already pointed out in an earlier post. In a default Spring setup, an @Autowired class instantiated with the new keyword will behave just like in an enterprise application: all the dependencies will be left untouched; they will not be injected but left with their default values (a.k.a. null). This, usually will end in a NullPointerException like in the example below:

public class CarSalon {
    //...
	public void testDrive() {
		Car car = new Car();
		car.startCar();
	}
}

@Component
public class Car {
	@Autowired
	private Engine engine;
	@Autowired
	private Transmission transmission;

	public void startCar() {
		transmission.setGear(1);
		engine.engineOn();
		System.out.println("Car started");
	}
}

@Component
public class Engine {
//...
}

@Component
public class Transmission {
//...
}

Yep, running this code will fail with a NullPointerException. However, unlike in JavaEE, in Spring there is an awesome way to inject dependencies into objects created with the new keyword: the @Configurable annotation.

In order to make the example above run, you should add the @Configurable annotation to the Car class like this:

@Configurable(preConstruction = true)
@Component
public class Car {

	@Autowired
	private Engine engine;
	@Autowired
	private Transmission transmission;

	public void startCar() {
		transmission.setGear(1);
		engine.engineOn();

		System.out.println("Car started");
	}
}


@Configurable(preConstruction = true) what an annotation! It tells Spring to inject dependencies into the object before the constructor is run. But wait a bit, this will not work just like that, out of the box. You still need to do several more things:

  1. Add the following jars to your classpath (Spring will use aspect orientation in order to work around default behavior, and make your object eligible for dependency injection): aspectj-x.x.x.jar, aspectjrt.jar, aspectjveawer-x.x.x.jar
  2. Add a Spring-based java agent to your run configuration like this: -javaagent:”PATH\spring-instrument-x.x.x.jar”

Aaaand pretty much that’s it. The code should now be running and printing “Car started”.