在Spring Boot中使用 @ConfigurationProperties 注解
Spring Boot 使用一些松的规则来绑定属性到@ConfigurationProperties bean 并且支持分层结构(hierarchical structure)。
1. 创建一个@ConfigurationProperties bean:
@ConfigurationProperties(prefix = "my",
ignoreUnknownFields = false,
locations = "classpath:my.yml")
public class ApplicationProperties {
public User user;
@data
public class ApplicationProperties {
private String userName;
private String passWord ;
}
}
2. 创建my.yml 文件
my:
user:
user-name: admin
pass-word: 123456
注: 使用my.properties 文件也可
上例中用到 @ConfigurationProperties 注解就可以绑定属性了。 prefix 用来选择哪个属性的prefix名字来绑定。ignoreUnknownFields = false 告诉 Spring Boot 在有属性不能匹配到声明的域的时候抛出异常(方便开发)。
但需要配合其他注解。可以搭配 @Configuration 注解来提供 @Beans 也可以单独使用并注入 @Configuration bean。
另一种也可使用,简化注解属性,然后用 Spring的@Autowire来注入 ApplicationProperties bean:
@ConfigurationProperties(prefix = "my",
ignoreUnknownFields = false)
public class ApplicationProperties {
public User user;
@data
public class User {
private String userName;
private String passWord ;
}
}
启动测试:
package com.yunwen.property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
@EnableConfigurationProperties({ApplicationProperties.class})
public class TestOne {
private static final Logger log = LoggerFactory.getLogger(TestOne.class);
@Autowired
private ApplicationProperties applicationProperties;
@GetMapping("/one")
public String one() {
log.info("applicationProperties: {}", applicationProperties);
return "ok";
}
public static void main(String[] args) {
//SpringApplication.run(TestOne.class, args);
new SpringApplicationBuilder(TestOne.class).web(true).run(args);
}
}
注: 请注意@EnableConfigurationProperties注解。该注解是用来开启对@ConfigurationProperties注解配置Bean的支持。也就是@EnableConfigurationProperties注解告诉Spring Boot 能支持@ConfigurationProperties。如果不指定会看到如下异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yunwen.property.ApplicationProperties] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
其他方法也可, 让@ConfigurationProperties beans 被添加 用@Configuration或者 @Component注解, 这样就可以在 component scan时候被发现。
转载并验证: https://www.cnblogs.com/duanxz/p/4520571.html
来源:oschina
链接:https://my.oschina.net/u/4545926/blog/4711389