方法1:通过Environment的getProperty的方法获取。
@Autowired
private Environment environment;
/**
* 1.通过Environment获取配置
* @return
*/
@GetMapping("/port")
public String port(){
return environment.getProperty("server.port");
}
方法2:通过@Value获取配置
/**
* 2.通过@Value获取配置
*/
@Value("${server.port}")
private String port;
@GetMapping("/port2")
public String port2(){
return port;
}
方法3:自定义配置类,prefix定义配置的前缀。
MyConfig.java
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author yuan
* @date 2019/2/13
* @description 自定义配置类
*/
@ConfigurationProperties(prefix = "com.test")
@Component
@Data
public class MyConfig {
private String name;
}
使用:
@Autowired
private MyConfig myConfig;
/**
* 3.自定义配置
*/
@GetMapping("/name")
public String getName(){
return myConfig.getName();
}
在application.properties中配置: