springboot 自动注入属性值到类中

1,303 阅读1分钟

springboot自动注入

/**
 * @Description 加载七牛云配置信息
 * @Author CoderZzz
 * @Date 2018/12/18 17:47
 */
@ConfigurationProperties(prefix = "oss.qiniu")//指定配置文件中前缀
@Component//必须是bean才能注入
@PropertySource("classpath:config/oos.properties")
public class QiniuConfig {
    private String appid;
    private String secret;
    private String bucket;
    private String domain;
}

会自动注入classpath:config/oos.properties(yml)文件的属性到QiniuConfig的属性中;

oss.qiniu.appid=KKa7agnpPJFKAhxYMjFbt3w6A9f5EOK9Myambrhi
oss.qiniu.secret=KdeTqKqNVPGRna1GbK2_ZTQuBhKf8mpa8k9JJX6I
oss.qiniu.bucket=overstep
oss.qiniu.domain=http://images.overstep.top/
  • 1 . 属性值若为静态的,要提供setter方法.
  • 2 . 属性值若为驼峰,在配置文件中写成全小写用-分割
  • 3 .可以注入List Set Map

可引入maven依赖后,就可以自动提示了(idea,警号时引入也有效)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>