在实际开发中,我们可能会遇到这样的场景,数据库的用户名和密码明文存储非常不安全,一种可行的方法是:运行时候通过访问一个安全性高的内部服务去获取用户名和密码.
配置如下:
application-Context.xml
<!--配置PropertyPlaceholderConfigurer -->
<bean class="xxxx.DBConnectionConfigurer">
<property name="fetcher" ref="fetcher"></property>
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource.master"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="${master_jdbc_url}"></property>
<property name="username" value="${master_jdbc_username}"></property>
...............
</bean>
db.properties
master_jdbc_url=database_master_jdbc_url
master_jdbc_username=database_master_jdbc_username
原理
通过DBConnectionConfigurer
来获取指定的key的value, 然后注入给数据源<bean id="dataSource.master". DBConnectionConfigurer继承自PropertyPlaceholderConfigurer, PropertyPlaceholderConfigurer向上追溯发现实现接口BeanFactoryPostProcessor,这个接口在Spring中有特殊的作用分析Spring代码
首先看AbstractApplicationContext, 这个类实现代码如下
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
在refresh函数中调用了函数invokeBeanFactoryPostProcessors
, 这个函数会调用PostProcessorRegistrationDelegate
类的invokeBeanFactoryPostProcessors
函数
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<String>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
new LinkedList<BeanDefinitionRegistryPostProcessor>();
// 硬编码注册的后处理器
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryPostProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
registryPostProcessors.add(registryPostProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// 配置注册的后处理器
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
registryPostProcessors.addAll(priorityOrderedPostProcessors);
invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(beanFactory, orderedPostProcessors);
registryPostProcessors.addAll(orderedPostProcessors);
invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
registryPostProcessors.add(pp);
processedBeans.add(ppName);
pp.postProcessBeanDefinitionRegistry(registry);
reiterate = true;
}
}
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(beanFactory, orderedPostProcessors);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
注意, 下文中的"后处理器"都是表示BeanFactoryPostProcessor
- 流程分析:
-
处理硬编码的后处理器,
- 判断硬编码的后处理器类型
- 如果是
BeanDefinitionRegistryPostProcessor
类型则加入到registryPostProcessors
中,并且同时处理这个registryPostProcessor
- 否则加入到
regularPostProcessors
中
- 如果是
- 判断硬编码的后处理器类型
-
从beanFactory中获取(不是硬编码的)所有类型为
BeanDefinitionRegistryPostProcessor
的bean, 并进行处理1.获得这些bean中具有PriorityOrdered属性的bean, 然后将这些bean添加到
priorityOrderedPostProcessors
中, 进行排序, 记录在processedBeans
中, 并批量执行这些后处理器.2.获得这些bean中具有Ordered属性的bean, 记录在
processedBeans
中, 然后将这些bean记录到orderedPostProcessors
中, 排序并执行.3.获得这些bean中不满足上述条件的bean, 记录在
processedBeans
中, 并依次执行4.批量处理
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
值得注意的是: 上述每个小步骤都会重新获得所有满足条件的bean集合, 即调用
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
,我的理解是在后处理器处理过程中,可能会生成新的BeanDefinitionRegistryPostProcessor
类型的后处理器, 所以需要重新加载, 此外, BeanDefinitionRegistryPostProcessor是特殊的后处理器, 在该阶段只执行特殊逻辑, 通用的逻辑在4中批量处理.
-
接下里处理bean容器中的
BeanFactoryPostProcessor
.- 对于获得的所有的
BeanFactoryPostProcessor
也同样按照级别去划分为priorityOrderedPostProcessors
,orderedPostProcessorNames
,nonOrderedPostProcessorNames
- 执行每个列表的时候都挨个去查找实际的class,然后遍历每个列表并执行
- 对于获得的所有的
-
一些特殊的操作
-
PropertyPlaceholderConfigurer
的执行过程如下
-
Properties mergedProps = mergeProperties();
// Convert the merged properties, if necessary.
convertProperties(mergedProps);
// Let the subclass process the properties.
processProperties(beanFactory, mergedProps);
首先是从locations指定的properties文件中读取内容, 然后获得调用convertProperties, 最终执行processProperties, convertProperties函数一般由自己完成逻辑,在processProperties中, 会调用BeanDefinitionVisitor, 遍历bean的各个属性用properties填充, BeanDefinitionVisitor会将替换的操作委托给内部的一个StringValueResolver
来执行(PlaceholderResolvingStringValueResolver
), 而这个StringValueResolver
又会将操作委托给PropertyPlaceholderHelper
, 这个helper(PropertyPlaceholderHelper
)在实际执行的时候会执行内部的parseStringValue
函数,解析过程可以参考源代码, 值得注意的是可能会在key里面嵌套新的key,例如${ty${key}}之类的,这种情况也处理了
此外,有一个特殊处理
if (propVal != null) {
// Recursive invocation, parsing placeholders contained in the
// previously resolved placeholder value.
propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
if (logger.isTraceEnabled()) {
logger.trace("Resolved placeholder '" + placeholder + "'");
}
startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length());
}
else if (this.ignoreUnresolvablePlaceholders) {
// Proceed with unprocessed value.
startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
}
else {
throw new IllegalArgumentException("Could not resolve placeholder '" +
placeholder + "'" + " in string value \"" + strVal + "\"");
}
visitedPlaceholders.remove(originalPlaceholder);
}
可见ignoreUnresolvablePlaceholders
这个参数有特殊的用途, 当我们定义多个PropertyPlaceholderConfigurer
时候, 可能是希望各自解析不同的内容,但是, 如果不指定ignoreUnresolvablePlaceholders
的时候,在执行第一个PropertyPlaceholderConfigurer
的时候,就会一直使用这个PropertyPlaceholderConfigurer
, 遇到不能解析的内容就会报错.这个需要特别注意一下