In Spring, it is a static variable, and the code block is injected

In Spring, it is a static variable, and the code block is injected

problem background

url1 was originally coded to death, and now it is necessary to inject parameters into url1, and at the same time give url1 to the static code block

    private static String url1 = "http://url1";
    private static HashMap<String,String> urls = new HashMap<>();

    static {
    
    
        urls.put("xxxUrl",url1);
    }

Solution

Execution priority (order): Constructor > @Value > @PostConstruct
Use @Value and @PostConstruct to resolve

@Value and the non-static set method can realize the assignment of the static variable url1, and then the operation of the map of urls needs to be executed after url1 is initialized, which can be realized by using @PostConstruct

    @Value("${spring.mail.host}")
    private static String url1 = "http://url1";

    private static HashMap<String,String> urls = new HashMap<>();

    @Value("${spring.mail.host}")
    public  void setUrl1(String url1) {
    
    
        ConTest.url1 = url1;
    }

    @PostConstruct
    public void init(){
    
    
        urls.put("xxxUrl",url1);
        System.out.println(urls);
    }

Guess you like

Origin blog.csdn.net/qq_50665031/article/details/126103424