It’s not because you can that you should…

Spring is an amazing framework with a lot of amazing features. One of these is the way you can access to the content of your properties files.
You remember? You put an annotation in a Spring managed bean, the name of the property and that’s it, you have the value of your property:

    @Value("${net.classnotfound.spring.user}")
    private String user;

That’s so simple that nothing prevent you from doing it wherever you need it, ending up with… Just a mess, if you want to rename (or remove) a property from your configuration file because you assume it is not used, you can just pray (and trust your test coverage)! Because you cannot be 100% sure that you removed it from wherever it has been used.
That’s why I always take care of the way we manage our properties.

My preferred way to manage properties is to define an unique class which will be responsible of the handling of the property, and I just inject this bean wherever I need. If I need to rename, I have only one place to look, if I decide to remove, I can simply remove the getter and the compiler will directly complain if it is still used somewhere in my application. Another aspect of this implementation is that it allows you to replace the implementation by another one in your test, for example.

OK, so, technically speaking, how does it work? Very simple, my unique class:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PropertyHandler {

	@Value("${net.classnotfound.spring.user}")
	private String user;

	public String getUser() {
		return user;
	}
}

And how to use it:

@Autowired
private PropertyHandler propertyHandler;

@RequestMapping("/handler")
public String boot() {
    return "Best wishes from Classnotfound to " + propertyHandler.getUser();
}

Yes, you can… But don’t 😉

A full example is available on this github repository

Leave a comment