Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize static injection in spring

Shulou Source: shulou.com Published: 2022-06-02 10:25:25 10月05日 Update

This article shows you how to achieve static injection in spring, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Spring implements static injection (class or property)

The scenario is that utility classes are generally static methods, and static methods can only access static properties. Therefore, we need to statically inject classes or properties.

General operation:

Inject a class or method:

@ Autowiredprivate TestService testService; [@ Resource] (https://my.oschina.net/u/929718)private TestService testService;@Value ("${key}") private String key

In this way, we inject the class in the container and the value in the Enviroment.

Static injection operation:

We inject it in the same way.

@ Autowiredprivate static TestService testService; [@ Resource] (https://my.oschina.net/u/929718)private static TestService testService;@Value ("${key}") private static String key

When we use static methods, null; will find that the injection does not go in.

There are two ways to solve the problem: (1) @ PostConstruct

@ Component public class TestUtil {@ Autowired private static TestService testService; private static TestUtil testUtils; @ PostConstruct public void init () {testUtils = this; testUtils.testService = this.testService;}}

The @ PostConstruct annotated method is executed after the class's constructor is loaded, that is, after the constructor is loaded, the init method is executed; (the @ PreDestroy annotation defines what is done before the container is destroyed.) this is similar to configuring the init-method and destory-method methods in xml, defining what the spring container does before initializing the bean and destroying the container.

(2) implementation of set method injection

@ Component public class TestUtil {private static TestService testService; private static String key; @ Value ("{key}") public void setTestService (String key) {TestUtil.key = key;} @ Autowired public void setTestService (TestService testService) {TestUtil.testService = this.testService }} the above is how to implement static injection in spring. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Static method container way attribute content function skill annotation knowledge same concise almost concise that is method scenario that is tool general Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info NVidia Shulou Information Shulou Technology Xiaomi