在Spring Boot中使用 @ConfigurationProperties 注解
开始创建一个@ConfigurationProperties bean:
1 | (locations = "classpath:mail.properties", |
…从如下属性中创建(mail.properties):
1 | mail.host=localhost |
方案一
1 |
|
方案二
1 |
|
注意: @EnableConfigurationProperties这个注解告诉Spring Boot能支持指定特定类型的@ConfigurationProperties。如果不指定会看到如下异常:
1 | org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [demo.mail.MailProperties] 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)} |
- 方案一不使用
@EnableConfigurationProperties注解,使用@Configuration或者@Component注解使其被component scan发现。 - 方案二使用
@EnableConfigurationProperties注解,使其指定的配置类被EnableConfigurationPropertiesImportSelector注册到应用上下文。

