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

在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:

扫描二维码关注公众号,回复: 479099 查看本文章
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

参考:http://www.javacodegeeks.com/2014/09/using-configurationproperties-in-spring-boot.html

猜你喜欢

转载自wenrisheng.iteye.com/blog/2231807