Spring Boot Util 工具类读取 application.properties
默认情况下,Spring Boot 的工具类是无法读取 application.properties 的内容的。
找了很多方法也没起作用,比如加 @Component , 设置成静态之类的。
后来看到高手的解决方法,原来还需要加个 Setter 。 特此记录一下,以备后用。
代码中去掉了 package 。
工具类: HelloUtil.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class HelloUtil {
private static String hello;
@Value("${hello}")
public void setHello(String hello) {
HelloUtil.hello = hello;
}
public static void hello() {
System.out.println(hello);
}
}
配置文件: application.properties
hello=hello, world!
Spring Boot 启动类:HelloApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloApp {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
HelloUtil.hello();
}
}
输出结果:
hello, world!