springboot访问配置文件的三种方式


1、读取配置文件的三种方式 @ConfigurationProperties(prefix = "my") 尽量指定前缀,避免冲突。
/** 第一种方式: 注入属性 */
@RestController
@ConfigurationProperties(prefix = "my")
public class PropController1 {

    private String host;
    private int port;
    private User user;
    private String[] address;
   private List users;
    /** 注入的属性必须提供setter方法 */
    get set 方法...
}
  2、@Value: 基本数据类型和String
/** 第二种方式: 注入属性 
    @Value注解的属性,不需要提供setter方法
    @Value只能注入: 基本数据类型与String
*/

@Value("${my.host}")
private String aaaHost;
@Value("${my.port}")
private int bbbPort;
  3、将需要注入的属性定义成一个属性类,当用到的时候 需要 启用配置属性。这样做属性类就可以重复使用。 @ConfigurationProperties: 配置属性 @EnableConfigurationProperties(UserProperties.class): 启用配置属性(创建对象)
/*  @ConfigurationProperties: 配置属性  */
@ConfigurationProperties(prefix = "my")
public class UserProperties {
    private String host;
    private int port;
    private User user;
    private String[] address;
    private List users;
}
/** 第三种方式: 注入属性
@EnableConfigurationProperties(UserProperties.class): 启用配置属性(创建对象)
  */
@RestController
@EnableConfigurationProperties(UserProperties.class)
public class PropController3 {

    @Autowired(required = false)
    private UserProperties userProperties;

    @GetMapping("/test3")
    public String test3(){
        System.out.println(userProperties.getHost());
        return "test3方法,访问成功!";
    }
}
   

相关