1. 注解在类上时
当@ConfigurationProperties
注解在类上时,并且此类同时注解@Component
,如下所示
@ConfigurationProperties(prefix = "account")
@Component
public class AccountProperties {
private String username;
private String password;
// 省略了get set方法
}
我可以直接通过@Autowired
注解在Bean
直接获取
@RestController
public class DemoController {
@Autowired
private AccountProperties accountProperties;
}
如果没有注解@Component
时,例如
@ConfigurationProperties(prefix = "account")
public class AccountProperties {
private String username;
private String password;
// 省略了get set方法
}
我们可以通过注解@EnableConfigurationProperties
获取,例如
@RestController
@EnableConfigurationProperties({AccountProperties.class})
public class DemoController {
@Autowired
private AccountProperties accountProperties;
}
2. 注解在方法上时
当注解在方法上,需配合@Bean
使用
@Configuration
public class DemoConfig {
@Bean
@ConfigurationProperties(prefix = "account")
public AccountProperties accountProperties() {
return new AccountProperties();
}
}
网友评论