springboot获取配置文件方式

springboot获取配置文件方式

默认配置获取方式

application.properties文件内容:
name=1
user.name=2

application.yml文件内容:
name: 1
user:
name: 2

方式一:通过@Value()获取

@Value("${name}")
private String name;

@Value("${user.name}")
private String userName;

设置默认值:

@Value("${name:张三}")
private String name;

//设置默认值为空置
@Value("${user.name:#{null}}")
private String userName;

方式二:通过@ConfigurationProperties(prefix="***")来读取

@Data
@Component
@ConfigurationProperties(prefix="user")
public class TestBean{
  String name;
}

自定义配置properties获取方式

例如test.properties:
name=1
user.name=2

方式一:通过@Value和@PropertySource结合取值

@Component
@PropertySource("classpath:test.properties")
public class TestBean{
  @Value("${name}")
  private String name;

  @Value("${user.name}")
  private String userName;
}

方式二:通过@ConfigurationProperties和@PropertySource结合取值

@Component
@ConfigurationProperties(prefix="user")
@PropertySource("classpath:test.properties")
public class TestBean{
  String name;
}

自定义配置yml获取方式

例如test.yml:
name: 1
user:
name: 2

方式一:通过@Value和@PropertySource

@Component
@PropertySource(value="test.yml",factory=PropertySourceFactory.class)
public class TestBean{
  @Value("${name}")
  private String name;
}

 

原文:https://blog.csdn.net/qq_34093116/article/details/123710936
 
posted @ 2022-06-28 16:21  liwinallucky  阅读(128)  评论(0)    收藏  举报