springboot静态属性读取配置文件

springboot 静态属性读取配置文件

yml配置

server:
  port: 8089

test:
  port: 8090

两种配置读取方式

  1. 非静态属性配置读取:依赖set方法
@Configuration
@ConfigurationProperties(prefix = "server") // 特别注意,依赖set方法
@Getter
@Setter
// CommandLineRunner 仅为测试
public class MyPropertity implements CommandLineRunner {

    private String port;

    public void sysout() {
        System.out.println(this.port);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("======= " + this.getClass().getName());
        sysout();
    }
}
  1. 静态属性配置读取:依赖非静态set方法
@Configuration
@ConfigurationProperties(prefix = "test") // 特别注意,依赖非静态set方法
public class MyStaticPropertity implements CommandLineRunner {

    private static String port;

    public static void sysout() {
        System.out.println(port);
    }

    public static String getPort() {
        return port;
    }

    /** 注意:静态属性读取关键点,非静态set方法 */
    public void setPort(String port) {
        MyStaticPropertity.port = port;
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("======= " + this.getClass().getName());
        sysout();
    }
}
  1. 关于@EnableConfigurationProperties注解使用说明
@SpringBootApplication
@EnableCaching
@EnableScheduling
// @EnableConfigurationProperties({MyStaticPropertity.class})  // 当MyStaticPropertity没有@[Bean]注解时,spring把MyStaticPropertity注入一次
public class DemoApplication {
    private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        SpringApplication.run(DemoApplication.class, args);
        logger.info("加载完成,启动耗时:{}", System.currentTimeMillis() - start);
    }
}

当MyStaticPropertity没有@[Bean] -> @Configuration注解时,spring把MyStaticPropertity注入一次

你可能感兴趣的:(springboot静态属性读取配置文件)