在做多数据切换的时候需要把配置属性映射成bean,2.X之后版本 public class DataImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware { private Environment environment; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { StandardEnvironment standardEnvironment = (StandardEnvironment)environment; Iterator<PropertySource<?>> sources = standardEnvironment.getPropertySources().iterator(); List<ConfigurationPropertySource> configs = new ArrayList<>(); while(sources.hasNext()){ PropertySource<?> source = sources.next(); Iterable<ConfigurationPropertySource> a = ConfigurationPropertySources.from(source); a.forEach(info->configs.add(info)); } Binder binder = new Binder(configs); try { //解析属性 BindResult<DataResources> response = binder.bind("jdbc", DataResources.class); binder = null;//释放 } catch (Exception e) { e.printStackTrace(); } } @Override public void setEnvironment(Environment environment) { this.environment = environment; } }
转载于:https://my.oschina.net/u/2504004/blog/2996156