Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use @ Value to assign values to static variables in SpringBoot

Shulou Source: shulou.com Published: 2022-06-02 11:07:56 09月22日 Update

How to use @ Value to assign values to static variables in SpringBoot, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Use the write method to get the configuration, but get a null.

@ Value ("${test.appKey}") private static String appKey

Only to find that it is not possible to take the configuration in this way to assign values to static variables.

After searching for a wave on the Internet, we can solve this problem by setter method or through the assignment of intermediate variables.

I used the setter method, the code is as follows:

Private static String appKey;@Value ("${test.appKey}") public void setAppKey (String appKey) {TestIt.appKey = appKey;}

It is important to note that you need to remove the static of the setAppKey method (if you use the setter method generated by generate in idea, you will have static like the variable, which you want to remove here)

When you're done, write a test class to simply test whether it works:

@ RunWith (SpringJUnit4ClassRunner.class) @ SpringBootTest@TestPropertySource (properties = {"spring.config.location = classpath:application-dev.yml"}) public class TestIt {private static String appKey; @ Value ("${test.appKey}") public void setAppKey (String appKey) {TestIt.appKey = appKey;} @ Test public void valueTest () {System.out.println ("forTest:" + appKey) }} this is the answer to the question about how to use @ Value to assign values to static variables in SpringBoot. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Tags: Methods variables questions static more help tests solutions configuration feasible easy easy code content writing guys partners ways knowledge articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Redmi Huawei Microsoft MySQL