Bean如非必要不必初始化
前言
Github:https://github.com/HealerJean
主要使用后置处理器(实现接口``BeanPostProcessor)、
@Conditional`,
比如:项目开发中KeyCenter其实在某些环境下不需要初始化为Bean,而且只在项目启动的时候修改数据库密码使用一次。如下文
1、Bean如非必要不必初始化
1.1、后置处理器
package com.fintech.pub.config.datasource;
import com.alibaba.druid.pool.DruidDataSource;
import com.xiaomi.mifi.common.utils.cryptor.KeyCenterCryptor;
import com.xiaomi.mifi.common.utils.db.DatabaseConnectionConfigurer;
import com.xiaomi.mifi.common.utils.db.keyproxy.KeyProxyClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
* @author HealerJean
* @ClassName DataSourcePostProcessor
* @date 2020/6/9 17:13.
* @Description
*/
@Conditional(DataSourceEncryptCondition.class)
@Component
@Slf4j
public class DataSourcePostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DruidDataSource) {
DruidDataSource druidDataSource = (DruidDataSource) bean;
encryptDataSource(druidDataSource);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
private void encryptDataSource(DruidDataSource druidDataSource) {
druidDataSource.setUrl(properties.getProperty("fintech.database.url"));
druidDataSource.setUsername(properties.getProperty("fintech.database.username"));
druidDataSource.setPassword(properties.getProperty("fintech.database.password"));
}
}
1.2、DataSourceEncryptCondition
@Configuration
@Slf4j
public class DataSourceEncryptCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
Environment environment = conditionContext.getEnvironment();
String encrypt = environment.getProperty("datasource.encrypt");
if (StringUtils.isNotBlank(encrypt) && "true".equals(encrypt)) {
return true;
}
return false;
}
}
1.3、properties
1.3.1、application.properties
####################################
### 引入模块
####################################
spring.profiles.active=db
1.3.2、application-db.properties
datasource.encrypt=false