Use configuration of SpringCloud unified configuration

  1. The way the configuration is read was mentioned in the previous article.
  2. After getting the value, assign it to the static variable in the static class.
  3. Because the SpringCloud project will execute all the APIs once (quite painful), so here you can directly write a method to assign values.

code show as below:

Entry class:

package com.shinho;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.alibaba.fastjson.JSON;
import com.shinho.log.ShinhoLog;

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages={"com.shinho"})
@EnableWebMvc
@EnableEurekaClient
@RestController
public class KylintestApplication {

    @Value("${foo}")
    String foo;
    
    private static final Logger logger = LoggerFactory.getLogger(KylintestApplication.class);
    
    public static void main(String[] args) {
        SpringApplication.run(KylintestApplication.class, args);
    }
    
    @RequestMapping("/log")
    @Bean
    public String Log() {
        logger.info("init:log");
        ShinhoLog.foo = this.foo;
        String json = "log";
        return json;
    }
    
    @RequestMapping("/hi")
    @Bean
    public String home() {
        String json = "123:"+ShinhoLog.info();
        return json;
    }
}

static class:

package com.shinho.log;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Component;

@Component
public class ShinhoLog {
    
    public static String foo;
    
    public static String info(){
        return foo;
    }
    
}

Visit http://localhost:XXXX/hi immediately after startup and it will return 123:foo version 2, perfect!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325270611&siteId=291194637