Spring annotations static injection tutorial
Spring’s architecture isn’t very friendly to static classes and methods. It doesn’t have any way of injecting static properties of classes because it doesn’t have any way to discover them. Spring’s designers have acknowledged that it’s a shortcoming of the framework and suggest the use of this solution.
- Create the static property of the class without any annotations
- Mark the class to have static properties injected with @Component so that the properties will be injected on Spring startup
- Create a non-static setter method that sets the static property
- Mark the setter method with @Autowired(required = true)
@Component
public class UserUtils
{
private static UserAccessor userAccessor;
/**
* Sets the user DAO. This method should never be called except by Spring
* @param userAccessor The user accessor to set
*/
@Autowired(required = true)
public void setUserAccessor(userAccessor UserAccessor) {
UserUtils.userAccessor = userAccessor;
}
}Using this technique, you can have all of the advantages of Spring injection without the headaches of Spring injection! Use it wisely, though. With a lot of statically stored values, your application will not scale well.



I always considered Spring’s lack of static injection a feature.The semantics of static properties and especially singletons are often not fully understood and can result in very obscure problems and assumptions. This is especially true when serialization, persistence and remoting are involved.
My rule is: never use static properties unless their value is guaranteed never to change ever for the life of the universe.
Spring has a better option – define an object to be a singleton within some context e.g. the application context. Then we can tidy up the semantics for persistence and clustering and not use statics.
Just my 2c.