在實際開發(fā)中,我們可能會遇到這樣的場景,數(shù)據(jù)庫的用戶名和密碼明文存儲非常不安全,一種可行的方法是:運(yùn)行時候通過訪問一個安全性高的內(nèi)部服務(wù)去獲取用戶名和密碼.
配置如下:
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>
<!-- 配置數(shù)據(jù)源 -->
<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, 然后注入給數(shù)據(jù)源<bean id="dataSource.master". DBConnectionConfigurer繼承自PropertyPlaceholderConfigurer, PropertyPlaceholderConfigurer向上追溯發(fā)現(xiàn)實現(xiàn)接口BeanFactoryPostProcessor,這個接口在Spring中有特殊的作用分析Spring代碼
首先看AbstractApplicationContext, 這個類實現(xiàn)代碼如下
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函數(shù)中調(diào)用了函數(shù)invokeBeanFactoryPostProcessors
, 這個函數(shù)會調(diào)用PostProcessorRegistrationDelegate
類的invokeBeanFactoryPostProcessors
函數(shù)
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, 并進(jìn)行處理1.獲得這些bean中具有PriorityOrdered屬性的bean, 然后將這些bean添加到
priorityOrderedPostProcessors
中, 進(jìn)行排序, 記錄在processedBeans
中, 并批量執(zhí)行這些后處理器.2.獲得這些bean中具有Ordered屬性的bean, 記錄在
processedBeans
中, 然后將這些bean記錄到orderedPostProcessors
中, 排序并執(zhí)行.3.獲得這些bean中不滿足上述條件的bean, 記錄在
processedBeans
中, 并依次執(zhí)行4.批量處理
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
值得注意的是: 上述每個小步驟都會重新獲得所有滿足條件的bean集合, 即調(diào)用
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
,我的理解是在后處理器處理過程中,可能會生成新的BeanDefinitionRegistryPostProcessor
類型的后處理器, 所以需要重新加載, 此外, BeanDefinitionRegistryPostProcessor是特殊的后處理器, 在該階段只執(zhí)行特殊邏輯, 通用的邏輯在4中批量處理.
-
接下里處理bean容器中的
BeanFactoryPostProcessor
.- 對于獲得的所有的
BeanFactoryPostProcessor
也同樣按照級別去劃分為priorityOrderedPostProcessors
,orderedPostProcessorNames
,nonOrderedPostProcessorNames
- 執(zhí)行每個列表的時候都挨個去查找實際的class,然后遍歷每個列表并執(zhí)行
- 對于獲得的所有的
-
一些特殊的操作
-
PropertyPlaceholderConfigurer
的執(zhí)行過程如下
-
Properties mergedProps = mergeProperties();
// Convert the merged properties, if necessary.
convertProperties(mergedProps);
// Let the subclass process the properties.
processProperties(beanFactory, mergedProps);
首先是從locations指定的properties文件中讀取內(nèi)容, 然后獲得調(diào)用convertProperties, 最終執(zhí)行processProperties, convertProperties函數(shù)一般由自己完成邏輯,在processProperties中, 會調(diào)用BeanDefinitionVisitor, 遍歷bean的各個屬性用properties填充, BeanDefinitionVisitor會將替換的操作委托給內(nèi)部的一個StringValueResolver
來執(zhí)行(PlaceholderResolvingStringValueResolver
), 而這個StringValueResolver
又會將操作委托給PropertyPlaceholderHelper
, 這個helper(PropertyPlaceholderHelper
)在實際執(zhí)行的時候會執(zhí)行內(nèi)部的parseStringValue
函數(shù),解析過程可以參考源代碼, 值得注意的是可能會在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
這個參數(shù)有特殊的用途, 當(dāng)我們定義多個PropertyPlaceholderConfigurer
時候, 可能是希望各自解析不同的內(nèi)容,但是, 如果不指定ignoreUnresolvablePlaceholders
的時候,在執(zhí)行第一個PropertyPlaceholderConfigurer
的時候,就會一直使用這個PropertyPlaceholderConfigurer
, 遇到不能解析的內(nèi)容就會報錯.這個需要特別注意一下