spring 条件化配置

步骤一:

实现接口:org.springframework.context.annotation.Condition

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class MyJdbcTc implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
try {
    //你需要加载的类权限的名称,或者指定的某些条件
conditionContext.getClassLoader().loadClass("java.lang.Object");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}

步骤二:
再Bean方法或者类上使用org.springframework.context.annotation.Conditional注解
@Configuration
public class MyConfig {
@Bean
@Conditional(MyJdbcTc.class)
public User user(){
User user = new User();
user.setId(1);
user.setName("hello");
return user;
}
}
posted @ 2019-05-13 17:56  陈标  阅读(415)  评论(0编辑  收藏  举报