1 基础用法,使用@Value注解直接注入配置信息
@Value("${spring.datasource.username}") private String name;
2 使用注解@Autowired注入Environment类
@Autowired private Environment environment; String username = environment.getProperty("spring.datasource.username");
3 定义一个工具类,使用@Component注解成为配置类,再继承ApplicationRunner 重写run(),再注入Environment 类获取配置,可以做到在任何地方随时随地获取配置信息
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @Order(2) public class BaseConfig implements ApplicationRunner { @Autowired private Environment environment; public static String port; @Override public void run(ApplicationArguments args) throws Exception { port=environment.getProperty("server.port"); System.out.println("------ " + port); } }
使用的时候直接调用静态类,程序一次读取,使用的时候调用
标签:environment,配置文件,Spring,Boot,springframework,Environment,import,org,port From: https://www.cnblogs.com/chengxin1982/p/16848249.html