springboot

来源:互联网 发布:java九九乘法表上三角 编辑:程序博客网 时间:2024/06/14 17:14

Type-safe Configuration Properties

在注入属性的时候,可以使用@Value(“${property}”),这种方式很方便,但也有不足,如果属性较多或者存在继承结构,那么@Value方式就显得力不从心。Spring Boot 提供了另一种方式来配置属性,使用@ConfigurationProperties。

使用:

1、配置文件application.properties如下:

foo.enabled=truefoo.remote-address=localhostfoo.security.username=zhangsanfoo.security.password=123456foo.security.roles=manager

2、定义一个与配置对应的类,所有以foo开头的属性都会被注入到FooPeroperties类。

@ConfigurationProperties(prefix = "foo")public class FooProperties {    private boolean enabled;    private InetAddress remoteAddress;    private final Security security = new Security();    public boolean isEnabled() { ... }    public void setEnabled(boolean enabled) { ... }    public InetAddress getRemoteAddress() { ... }    public void setRemoteAddress(InetAddress remoteAddress) { ... }    public Security getSecurity() { ... }    public static class Security {        private String username;        private String password;        private List<String> roles = new ArrayList<>(Collections.singleton("USER"));        public String getUsername() { ... }        public void setUsername(String username) { ... }        public String getPassword() { ... }        public void setPassword(String password) { ... }        public List<String> getRoles() { ... }        public void setRoles(List<String> roles) { ... }    }}

3、 接下来有两种方式配置FooPeroperties:

  • 一种就是常规的配置bean的方式
@Component@ConfigurationProperties(prefix="foo")public class FooProperties {    // ... see above}
  • 另外一种就是使用@EnableConfigurationProperties
@Configuration@EnableConfigurationProperties(FooProperties.class)public class MyConfiguration {}

4、注入@ConfigurationProperties配置的bean和常规的注入bean方式一样

@Servicepublic class MyService {    private final FooProperties properties;    @Autowired    public MyService(FooProperties properties) {        this.properties = properties;    }     //...    @PostConstruct    public void openConnection() {        Server server = new Server(this.properties.getRemoteAddress());        // ...    }}
Third-party configuration

@ConfigurationProperties不仅可以标注在一个类上,同样可以标注一个@Bean方法上,尤其需要将属性绑定到不在你控制之内的第三方组件。

@ConfigurationProperties(prefix = "bar")@Beanpublic BarComponent barComponent() {    ...}
Relaxed binding

@ConfigurationProperties属性匹配是不是精确匹配,例如这个@ConfigurationProperties类

@ConfigurationProperties(prefix="person")public class OwnerProperties {    private String firstName;    public String getFirstName() {        return this.firstName;    }    public void setFirstName(String firstName) {        this.firstName = firstName;    }}

下面的属性名都可以适配

  • person.firstName
  • person.first-name
  • person.first_name
  • PERSON_FIRST_NAME
原创粉丝点击