Spring – How to Autowire bean in a static class

Spring – How to Autowire bean in a static class

There are situations in witch you need to access Spring ApplicationContext or any other Spring bean from a static method.

The problem

We have a static utility class called StaticUtils which looks like below:

As you can see there is an @Autowired annotation in the 5th line and we expect that Spring inject a proper bean here.

Below is an example MyConfig class used in the utility class. It requires to pass foo property.

 

Let’s write an application class and to test it. Remember to pass -Dfoo=bar property.

The result is NullPointerException.

 

As you can see Spring is not able to inject beans directly to static class and the NullPointerException occurred.

 

The solution

There are several ways to achieve it, but some of them may fail when you run an application it in different conditions like passing application properties from command line instead of application properties file.

Using StaticContextInitializer class

The most elegant and quite safe method I’ve known is what I called StaticContextInitializer. The idea is to create component class called StaticContextInitializer, which is responsible to initialize static classes in its  @PostConstruct annotated method. Let’s see it in practice.

Step 1 – change utility class

Edit  StaticUtils class, remove the @Autowired annotation and add setter method for myConfig field. The class after changes should looks like below.

 

Step 2  – create StaticContextInitializer compoment

Create class called  StaticContextInitializer with init method annotated by @PostConstruct. Pass myConfig to the StaticUtils class.

 

Step 3 – test

Run the application once again and you will see the expected result.

 

If you think this post is valuable, please leave me +1  or share it. This action will allow me to reach a wider audience.

Thank you.

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Mike Hazelwood Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Mike Hazelwood
Guest
Mike Hazelwood

Nice article Łukasz. Thanks for putting this together and sharing it. It’s just what I needed.

Close Menu