SSM-Spring-Spring装配Bean-条件化装配Bean
- Spring中提供了@Conditional注解实现条件化是否装配bean,这样可以根据条件动态的装配bean;
- 要判定@Conditional 注解是否该装配bean还需要Condition 接口配合,我们只须实现 Condition 接口,重写matches 方法;
- 根据matches方法返回的布尔值进行判定@Conditional是否需要装配bean
//实现接口Condition
public class DataSourceCondition implements Condition {
//重写matches
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//获取上下文环境
Environment env = context.getEnvironment();
//判断是否存在关于数据源的基础配置
return env.containsProperty("jdbc.database.driver")
&& env.containsProperty("jdbc.database.url")
&& env.containsProperty("jdbc.database.username")
&& env.containsProperty("jdbc.database.password");
}
}
条件化装配数据源:
@Bean(name = "dataSource")
//通过传入实现Condition的类,调用重写matches方法,返回判断结果,true则装配Bean
@Conditional({DataSourceCondition.class})
public DataSource getDataSource(
@Value("${jdbc.database.driver}") String driver,
@Value("${jdbc.database.url}") String url,
@Value("${jdbc.database.username}") String username,
@Value("${jdbc.database.password}") String password) {
Properties props = new Properties();
props.setProperty("driver", driver);
props.setProperty("url", url);
props.setProperty("username", username);
props.setProperty("password", password);
DataSource dataSource = null;
try {
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}