昨天我們講述了條件註解,@ConditionalOnClass(@ConditionalOnMissingClass)他可以在類路徑下存在(不存在)XXX才注入到Container中,又或是@ConditionalOnBean(@ConditionalOnMissingBean)聲明Container中存在(不存在)XXXBean我們才將他注入。今日我們來說說如何把註冊的Bean與配置文件綁定。
public class Employee {
private String id;
private String name;
//getter&setter略
}
@SpringBootApplication
public class Day08BindingPropertiesApplication {
public static void main(String[] args) {
ApplicationContext ioc = SpringApplication.run(Day08BindingPropertiesApplication.class, args);
for (String s : ioc.getBeanNamesForType(Employee.class)) {
System.out.println(s);
System.out.println(ioc.getBean(s));
}
}
}
emp.id = 1
emp.name = james
boss.id = 99
boss.name = big boss
聲明組件的屬性和配置文件(Application.pro)的那些前綴開始綁定,此Annotation尚須將自己放入容器中,binding的方式有兩種
@ConfigurationProperties(prefix = "emp")
@Component
public class Employee {
//略
}
執行結果
2. 設置在在配置類中
@Configuration
public class AppConfig {
@ConfigurationProperties(prefix = "emp")
@Bean
public Employee emp(){
return new Employee();
}
@ConfigurationProperties(prefix = "boss")
@Bean
public Employee boss(){
return new Employee();
}
}
執行結果
啟動哪些類別與配置文件綁定並放到Container中。因SpringBoot預設只掃描自己package下的類別,所以在第三方套就可以透過這個方法將屬性綁定並註冊到Container中
@SpringBootApplication
@EnableConfigurationProperties(Employee.class)
public class Day08BindingPropertiesApplication {
//略
}
@ConfigurationProperties(prefix = "boss")
public class Employee {
//略
}
執行結果