Spring Conditional Annotations

Posted by Adam on August 24, 2022
### [Spring Conditional Annotations](https://www.baeldung.com/spring-conditional-annotations) ```java import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; public class SecondaryDataSourceCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { try { DataSource dataSource = context.getBeanFactory().getBean("secondaryDataSource", DataSource.class); Connection connection = dataSource.getConnection(); connection.close(); return true; } catch (SQLException ex) { return false; } } } ``` ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; @Configuration public class DataSourceConfig { @Bean(name = "primaryDataSource") public DataSource primaryDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/primary_db"); dataSource.setUsername("primary_user"); dataSource.setPassword("primary_pass"); return dataSource; } @Bean(name = "secondaryDataSource") @Conditional(SecondaryDataSourceCondition.class) public DataSource secondaryDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/secondary_db"); dataSource.setUsername("secondary_user"); dataSource.setPassword("secondary_pass"); return dataSource; } } ``` ### [The Spring @ConditionalOnProperty Annotation](https://www.baeldung.com/spring-conditionalonproperty) ```java @Configuration public class MyConfig { @Bean @ConditionalOnProperty(name = "my.property.enabled", havingValue = "true") public MyBean myBean() { return new MyBean(); } } ``` 在此示例中,當 my.property.enabled 屬性被設置為 true 時,myBean Bean 將被創建。如果屬性設置為其他值,則不會創建該 Bean。