Posts Tagged ‘Spring’

Spring annotations static injection tutorial

12 Comments »

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.

  1. Create the static property of the class without any annotations
  2. Mark the class to have static properties injected with @Component so that the properties will be injected on Spring startup
  3. Create a non-static setter method that sets the static property
  4. 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!  Avoid using this technique whenever possible.  It should only be used to support legacy applications.  With a lot of statically stored values, your application will not scale well.