您的位置:首页 > 编程语言 > Java开发

spring boot 注入properties属性文件的值 @ConfigurationProperties

2017-11-08 00:00 411 查看
在spring boot

1.建立一个普通的bean,利用@ConfigurationProperties:

@Configuration
@ConfigurationProperties(locations = "classpath:properyname.properties", prefix = "datasource")
public class PropertyBean {
@NotBlank
private String driverClassName;
@NotBlank
private String url;
@NotBlank
private String userName;

....................get、set方法

开启扫描此bean,spring application会生成一个PropertyBean

2.@ConfigurationProperties会绑定properties中的值,并且支持层级关系

@ConfigurationProperties(locations = "classpath:mail.properties",
ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {

public static class Smtp {

private boolean auth;
private boolean starttlsEnable;

// ... getters and setters
}

@NotBlank
private String host;
private int port;
private String from;
private String username;
private String password;
@NotNull
private Smtp smtp;


3.利用
@PropertySource注解


@Configuration
@PropertySource("classpath:mail.properties")
public class MailConfiguration {

@Value("${mail.protocol}")
private String protocol;
@Value("${mail.host}")
private String host;
@Value("${mail.port}")
private int port;
@Value("${mail.smtp.auth}")
private boolean auth;
@Value("${mail.smtp.starttls.enable}")
private boolean starttls;
@Value("${mail.from}")

spring boot 会自动注入mail.properties中的值

mail.properties:

mail.host=localhost
mail.port=25
mail.smtp.auth=false
mail.smtp.starttls-enable=false
mail.from=me@localhost
mail.username=
mail.password=


4.

@Configuration
@PropertySource("classpath:datasource.properties")
public class DataSourceConfig {

@Resource
private Environment env;

public void getValue() {

String name = env.getRequiredProperty("datasource.name");

}

datasource.properties:

datasource.username=root
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐