1、执行注入工具类
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static Boolean isBeanExit(String beanName) {
try {
applicationContext.getBean(beanName);
} catch (Exception e) {
return false;
}
return true;
}
public static Object registerSingletonBean(String beanName, Object singletonObject) {
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getAutowireCapableBeanFactory();
defaultListableBeanFactory.registerSingleton(beanName, singletonObject);
return configurableApplicationContext.getBean(beanName);
}
}
2、容器启动读取配置文件并调用注入方法
@Component
@Slf4j
public class AliyunDbFactory implements ApplicationListener<ContextRefreshedEvent> {
private final CloudDbProperties cloudDbProperties;
public AliyunDbFactory(CloudDbProperties cloudDbProperties) {
this.cloudDbProperties = cloudDbProperties;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
for (AliyunDb aliyun : cloudDbProperties.getAliyuns()) {
ApplicationContextUtil.registerSingletonBean("beanName", new Object());
}
}
}
3、配置类详情
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "xx.yy.zz")
public class CloudDbProperties {
private List<AliyunDb> aliyuns;
@Getter
@Setter
@ToString
public static class AliyunDb implements Serializable {
private String companyId;
private String ecsAccessKeyId;
private String ecsAccessSecret;
}
}
4、配置文件详情
xx:
yy:
zz:
aliyuns:
- company-id: 123
ecs-access-key-id: LTAI4Fmb3HCMWN59T7v2MBSD
ecs-access-secret: 4DbnjVGr7DQ1wWzForWppTzAUk6ppf
- company-id: 456
ecs-access-key-id: XXXXXXXXXXXXXX
ecs-access-secret: YYYYYYYYYYYYYYYY
|