昨天介紹了宣告為配置類的@Configuration、@SpringBootConfiguration以及常用註冊組件的@Controller、 @Service、@Repository、@Component,今天將進一步介紹@ConditionOnXXX,在條件成立下才執行動作,就讓我們來看看吧
一樣我們開專案後導入Spring Web場景
public class Employee {
private String id;
private String empName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
為了測試我們加載IBM MQ的套件
<!-- https://mvnrepository.com/artifact/com.ibm.mq/com.ibm.mq.allclient -->
<dependency>
<groupId>com.ibm.mq</groupId>
<artifactId>com.ibm.mq.allclient</artifactId>
<version>9.3.3.1</version>
</dependency>
@Import(MQChannelDefinition.class)
@SpringBootApplication
public class Day07ConditionApplication {
SpringApplication.run(Day07ConditionApplication.class, args);
}
@ConditionOnClass指的是如果類路徑存在就觸發指定行為,相反的Annotation就是@ConditionOnMissingClass,我們來利用昨天MQChannelDefinition來作範例導入不同的Employee吧
@Configuration
public class AppConfig {
@ConditionalOnClass(name = "com.ibm.mq.MQChannelDefinition")
@Bean
public Employee emp01(){
return new Employee();
}
@ConditionalOnMissingClass( value = "com.ibm.mq.MQChannelDefinition")
@Bean
public Employee emp02(){
return new Employee();
}
}
@ContitionalOnBean如果Container中存在这个Bean(组件),就觸發指定行為,相反的Annotation就是@ConditionOnMissingBean
//AppConfig再加入這兩的Bean
@ConditionalOnBean(name = "emp01")
@Bean
public Employee emp03(){
return new Employee();
}
@ConditionalOnMissingBean( name = "emp02")
@Bean
public Employee emp04(){
return new Employee();
}
將Maven引入的IBM MQ、@Import(MQChannelDefinition.class)註解掉再執行一次