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();
}
}