springboot自动装配核心原理:
通过@Condition注解,判断是否要将当前bean注册到spring容器。
@Condition用法:
一、@Condition放在@Bean
放在@Bean下面,动态判断是否需要注册bean,@Condition的判断逻辑写在其后括号中,示例代码如下:
public interface UserDAO {
....
}
public class JdbcUserDAO implements UserDAO {
....
}
public class MongoUserDAO implements UserDAO {
....
}
public class MySQLDatabaseTypeCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
String enabledDBType = System.getProperty("dbType"); // 获得系统参数 dbType
// 如果该值等于MySql,则条件成立
return (enabledDBType != null && enabledDBType.equalsIgnoreCase("MySql"));
}
}
// 与上述逻辑一致
public class MongoDBDatabaseTypeCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
String enabledDBType = System.getProperty("dbType");
return (enabledDBType != null && enabledDBType.equalsIgnoreCase("MongoDB"));
}
}
// 根据条件来注册不同的Bean
@Configuration
public class AppConfig {
@Bean
@Conditional(MySQLDatabaseTypeCondition.class)
public UserDAO jdbcUserDAO() {
return new JdbcUserDAO();
}
@Bean
@Conditional(MongoDBDatabaseTypeCondition.class)
public UserDAO mongoUserDAO() {
return new MongoUserDAO();
}
}
二、自定义注解中使用@Condition
step1:实现自定义注解
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(DatabaseTypeCondition.class)
public @interface DatabaseType {
String value();
}
step2:实现条件逻辑
public class DatabaseTypeCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata
.getAnnotationAttributes(DatabaseType.class.getName());
String type = (String) attributes.get("value");
// 默认值为MySql
String enabledDBType = System.getProperty("dbType", "MySql");
return (enabledDBType != null && type != null && enabledDBType.equalsIgnoreCase(type));
}
}
step3:使用自定义注解
@Configuration
@ComponentScan
public class AppConfig {
@Bean
@DatabaseType("MySql")
public UserDAO jdbcUserDAO() {
return new JdbcUserDAO();
}
@Bean
@DatabaseType("mongoDB")
public UserDAO mongoUserDAO() {
return new MongoUserDAO();
}
}
参考:
https://sylvanassun.github.io/2018/01/08/2018-01-08-spring_boot_auto_configure/