文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書
3.8 Container Extension Points
Typically, an application developer does not need to subclass ApplicationContext implementation classes. Instead, the Spring IoC container can be extended by plugging in implementations of special integration interfaces. The next few sections describe these integration interfaces.
通常情況下,應(yīng)用開發(fā)者不需要繼承ApplicationContext的實(shí)現(xiàn)類。反而是Spring的IoC容器可以通過插入特定集成接口的實(shí)現(xiàn)來進(jìn)行擴(kuò)展。下面幾節(jié)將描述這些集成接口。
3.8.1 Customizing beans using a BeanPostProcessor
The BeanPostProcessor interface defines callback methods that you can implement to provide your own (or override the container’s default) instantiation logic, dependency-resolution logic, and so forth. If you want to implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean, you can plug in one or more BeanPostProcessor implementations.
BeanPostProcessor接口定義了回調(diào)方法,你可以實(shí)現(xiàn)這個(gè)方法來提供你自己的(或覆蓋容器默認(rèn)的)實(shí)例化邏輯,依賴解析邏輯等等。如果你想在Spring容器完成實(shí)例化,配置和初始化bean之后實(shí)現(xiàn)一些定制的業(yè)務(wù)邏輯,你可以插入一個(gè)或多個(gè)BeanPostProcessor實(shí)現(xiàn)。
You can configure multiple BeanPostProcessor instances, and you can control the order in which these BeanPostProcessors execute by setting the order property. You can set this property only if the BeanPostProcessor implements the Ordered interface; if you write your own BeanPostProcessor you should consider implementing the Ordered interface too. For further details, consult the javadocs of the BeanPostProcessor and Ordered interfaces. See also the note below on programmatic registration of BeanPostProcessors.
你可以配置多個(gè)BeanPostProcessor實(shí)例,通過設(shè)置order屬性你可以控制BeanPostProcessors的執(zhí)行順序。只有BeanPostProcessor實(shí)現(xiàn)了Ordered接口時(shí)你才可以設(shè)置這個(gè)屬性;如果你編寫了你自己的BeanPostProcessor,你也應(yīng)該考慮實(shí)現(xiàn)Ordered接口。更多細(xì)節(jié)請參考BeanPostProcessor接口和Ordered接口的Java文檔。也可以查看下面的BeanPostProcessors編程注冊的筆記。
BeanPostProcessorsoperate on bean (or object) instances; that is to say, the Spring IoC container instantiates a bean instance and thenBeanPostProcessorsdo their work.
BeanPostProcessorsare scoped per-container. This is only relevant if you are using container hierarchies. If you define aBeanPostProcessorin one container, it will only post-process the beans in that container. In other words, beans that are defined in one container are not post-processed by aBeanPostProcessordefined in another container, even if both containers are part of the same hierarchy.
To change the actual bean definition (i.e., the blueprint that defines the bean), you instead need to use a
BeanFactoryPostProcessoras described in Section 3.8.2, “Customizing configuration metadata with a BeanFactoryPostProcessor”.
?
BeanPostProcessors操作一個(gè)bean(或?qū)ο螅?shí)例;也就是說,Spring Ioc容器實(shí)例化一個(gè)bean實(shí)例,然后BeanPostProcessors完成它們的工作。
BeanPostProcessors的作用域是每個(gè)容器。只有你在使用容器分層的情況下,這才是相關(guān)的。如果你在一個(gè)容器中定義了一個(gè)BeanPostProcessor,它將只后處理容器中的beans。換句話說,某個(gè)容器中定義的beans不能被另一個(gè)容器中定義的BeanPostProcessor進(jìn)行后處理,即使這兩個(gè)容器是同一層上的一部分。
為了改變實(shí)際的bean定義(例如,定義bean的藍(lán)圖),你可以使用3.8.2小節(jié)中描述的
BeanFactoryPostProcessor。
The org.springframework.beans.factory.config.BeanPostProcessor interface consists of exactly two callback methods. When such a class is registered as a post-processor with the container, for each bean instance that is created by the container, the post-processor gets a callback from the container both before container initialization methods (such as InitializingBean’s afterPropertiesSet() and any declared init method) are called as well as after any bean initialization callbacks. The post-processor can take any action with the bean instance, including ignoring the callback completely. A bean post-processor typically checks for callback interfaces or may wrap a bean with a proxy. Some Spring AOP infrastructure classes are implemented as bean post-processors in order to provide proxy-wrapping logic.
org.springframework.beans.factory.config.BeanPostProcessor接口包含恰好兩個(gè)回調(diào)方法。當(dāng)這樣一個(gè)類在容器中注冊為后處理器時(shí),對于容器中創(chuàng)建的每一個(gè)bean實(shí)例,在容器初始化方法(例如InitializingBean的afterPropertiesSet()方法和任何已聲明的初始化方法)被調(diào)用之前和任何bean初始化回調(diào)函數(shù)之后,后處理器會從容器中得到一個(gè)回調(diào)函數(shù)。后處理器可以對bean實(shí)例進(jìn)行任何操作,包括完全忽略回調(diào)方法。bean后處理器通常檢查回調(diào)接口或?qū)ean包裹到代理中。為了提供代理包裹邏輯,一些Spring AOP基礎(chǔ)結(jié)構(gòu)類被實(shí)現(xiàn)為bean后處理器。
An ApplicationContext automatically detects any beans that are defined in the configuration metadata which implement the BeanPostProcessor interface. The ApplicationContext registers these beans as post-processors so that they can be called later upon bean creation. Bean post-processors can be deployed in the container just like any other beans.
ApplicationContext會自動檢測任何配置元數(shù)據(jù)中定義的實(shí)現(xiàn)了BeanPostProcessor接口的bean。為了能在后面bean創(chuàng)建時(shí)調(diào)用這些bean,ApplicationContext會將這些bean注冊為后處理器。bean后處理器可以像其它bean一樣在容器進(jìn)行部署。
Note that when declaring a BeanPostProcessor using an @Bean factory method on a configuration class, the return type of the factory method should be the implementation class itself or at least the org.springframework.beans.factory.config.BeanPostProcessor interface, clearly indicating the post-processor nature of that bean. Otherwise, the ApplicationContext won’t be able to autodetect it by type before fully creating it. Since a BeanPostProcessor needs to be instantiated early in order to apply to the initialization of other beans in the context, this early type detection is critical.
注意當(dāng)在一個(gè)配置類上使用@Bean聲明一個(gè)BeanPostProcessor時(shí),工廠方法的返回值應(yīng)該是實(shí)現(xiàn)類本身或是org.springframework.beans.factory.config.BeanPostProcessor接口,這能清晰的表明bean的后處理器特性。此外,在完整的創(chuàng)建它之前,ApplicationContext不能通過類型自動檢測它。由于BeanPostProcessor需要早一點(diǎn)實(shí)例化,為了在上下文中初始化其它的beans,早期的類型檢測是非常關(guān)鍵的。
While the recommended approach for
BeanPostProcessorregistration is throughApplicationContextauto-detection (as described above), it is also possible to register them programmatically against aConfigurableBeanFactoryusing theaddBeanPostProcessormethod. This can be useful when needing to evaluate conditional logic before registration, or even for copying bean post processors across contexts in a hierarchy. Note however thatBeanPostProcessorsadded programmatically do not respect theOrderedinterface. Here it is the order of registration that dictates the order of execution. Note also thatBeanPostProcessorsregistered programmatically are always processed before those registered through auto-detection, regardless of any explicit ordering.
?
雖然推薦的注冊
BeanPostProcessor的方法是通過ApplicationContext自動檢測(像前面描述的那樣),但也可以通過以編程方法通過使用ConfigurableBeanFactory的addBeanPostProcessor方法來注冊。在注冊之前需要評估條件邏輯時(shí),這是非常有用的,或者通過分層中的上下文來復(fù)制bean后處理器。注意以編程方式添加的BeanPostProcessors不需要Ordered接口。這種情況下注冊順序意味著執(zhí)行順序。注意以編程方式注冊的BeanPostProcessors中是在那些通過自動檢測注冊的BeanPostProcessors之前進(jìn)行處理,不管任何顯式的順序指定。
?
Classes that implement the
BeanPostProcessorinterface are special and are treated differently by the container. AllBeanPostProcessorsand beans that they reference directly are instantiated on startup, as part of the special startup phase of theApplicationContext. Next, allBeanPostProcessorsare registered in a sorted fashion and applied to all further beans in the container. Because AOP auto-proxying is implemented as aBeanPostProcessoritself, neitherBeanPostProcessorsnor the beans they reference directly are eligible for auto-proxying, and thus do not have aspects woven into them.
For any such bean, you should see an informational log message: "Bean foo is not eligible for getting processed by all
BeanPostProcessorinterfaces (for example: not eligible for auto-proxying)".
Note that if you have beans wired into your
BeanPostProcessorusing autowiring or@Resource(which may fall back to autowiring), Spring might access unexpected beans when searching for type-matching dependency candidates, and therefore make them ineligible for auto-proxying or other kinds of bean post-processing. For example, if you have a dependency annotated with@Resourcewhere thefield/settername does not directly correspond to the declared name of a bean and no name attribute is used, then Spring will access other beans for matching them by type.
?
實(shí)現(xiàn)
BeanPostProcessor接口的類是特別的并被容器不同對待。所有的BeanPostProcessors和它們直接引用的beans在啟動時(shí)進(jìn)行實(shí)例化,它們是ApplicationContext特定啟動階段的一部分。接下來,所有BeanPostProcessors以有序形式進(jìn)行注冊,并適用于容器中所有更進(jìn)一步的beans。由于AOP自動代理是作為BeanPostProcessor本身實(shí)現(xiàn)的,既不是BeanPostProcessors也不是它們直接引用的beans適合進(jìn)行自動代理,因此沒有融入它們的方面。
對于這樣的bean,你應(yīng)該看到一個(gè)信息日志消息:"Bean foo沒資格被所有的
BeanPostProcessor接口進(jìn)行處理(例如,不適合自動代理)。"。
注意如果有beans使用自動裝配或
@Resource(可能回到自動裝配)注入你的BeanPostProcessor,當(dāng)搜索類型匹配的依賴候選者時(shí),Spring可能訪問未預(yù)料到beans,因此使它們不適合自動代理或其他類型的進(jìn)行后處理的bean。例如,如果你有一個(gè)帶有@Resource注解的依賴,field/setter名稱不能直接對應(yīng)bean聲明的名字,也沒有使用name特性,Spring將通過類型匹配來訪問其它的bean。
The following examples show how to write, register, and use BeanPostProcessors in an ApplicationContext.
下面的例子展示了在ApplicationContext中如何編寫,注冊和使用BeanPostProcessors。
Example: Hello World, BeanPostProcessor-style
This first example illustrates basic usage. The example shows a custom BeanPostProcessor implementation that invokes the toString() method of each bean as it is created by the container and prints the resulting string to the system console.
第一個(gè)例子闡述了基本用法。這個(gè)例子展示了一個(gè)定制BeanPostProcessor實(shí)現(xiàn),實(shí)現(xiàn)中調(diào)用了每一個(gè)bean的toString()方法。當(dāng)容器創(chuàng)建它時(shí),會將結(jié)果字符串輸出到系統(tǒng)控制臺。
Find below the custom BeanPostProcessor implementation class definition:
下面是定制BeanPostProcessor實(shí)現(xiàn)的類定義:
package scripting;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;
public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor {
// simply return the instantiated bean as-is
public Object postProcessBeforeInitialization(Object bean,
String beanName) throws BeansException {
return bean; // we could potentially return any object reference here...
}
public Object postProcessAfterInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("Bean '" + beanName + "' created : " + bean.toString());
return bean;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd">
<lang:groovy id="messenger"
script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy">
<lang:property name="message" value="Fiona Apple Is Just So Dreamy."/>
</lang:groovy>
<!--
when the above bean (messenger) is instantiated, this custom
BeanPostProcessor implementation will output the fact to the system console
-->
<bean class="scripting.InstantiationTracingBeanPostProcessor"/>
</beans>
Notice how the InstantiationTracingBeanPostProcessor is simply defined. It does not even have a name, and because it is a bean it can be dependency-injected just like any other bean. (The preceding configuration also defines a bean that is backed by a Groovy script. The Spring dynamic language support is detailed in the chapter entitled Chapter 31, Dynamic language support.)
注意InstantiationTracingBeanPostProcessor是怎樣簡單定義的。它甚至沒有一個(gè)名字,因?yàn)樗且粋€(gè)bean,它能像其它bean一樣進(jìn)行依賴注入。(前面的配置也定義了一個(gè)bean,它被Groovy腳本支持。Spring動態(tài)語言支持在31章『動態(tài)語言支持』中進(jìn)行了詳細(xì)描述。)
The following simple Java application executes the preceding code and configuration:
下面的簡單Java應(yīng)用執(zhí)行了前面的代碼和配置:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;
public final class Boot {
public static void main(final String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("scripting/beans.xml");
Messenger messenger = (Messenger) ctx.getBean("messenger");
System.out.println(messenger);
}
}
The output of the preceding application resembles the following:
前面的應(yīng)用輸出結(jié)果如下:
Bean 'messenger' created : org.springframework.scripting.groovy.GroovyMessenger@272961
org.springframework.scripting.groovy.GroovyMessenger@272961
Example: The RequiredAnnotationBeanPostProcessor
Using callback interfaces or annotations in conjunction with a custom BeanPostProcessor implementation is a common means of extending the Spring IoC container. An example is Spring’s RequiredAnnotationBeanPostProcessor - a BeanPostProcessor implementation that ships with the Spring distribution which ensures that JavaBean properties on beans that are marked with an (arbitrary) annotation are actually (configured to be) dependency-injected with a value.
使用回調(diào)函數(shù)接口或注解結(jié)合定制BeanPostProcessor實(shí)現(xiàn)是擴(kuò)展Spring IoC容器的常見方法。一個(gè)例子是Spring的RequiredAnnotationBeanPostProcessor——一個(gè)BeanPostProcessor實(shí)現(xiàn)附帶在Spring發(fā)行中,它保證了標(biāo)記有(任意)注解的beans上的JavaBean屬性能真正(配置成)通過值進(jìn)行依賴注入。
3.8.2 Customizing configuration metadata with a BeanFactoryPostProcessor
The next extension point that we will look at is the org.springframework.beans.factory.config.BeanFactoryPostProcessor. The semantics of this interface are similar to those of the BeanPostProcessor, with one major difference: BeanFactoryPostProcessor operates on the bean configuration metadata; that is, the Spring IoC container allows a BeanFactoryPostProcessor to read the configuration metadata and potentially change it before the container instantiates any beans other than BeanFactoryPostProcessors.
接下來我們要看到的擴(kuò)展點(diǎn)是org.springframework.beans.factory.config.BeanFactoryPostProcessor。這個(gè)接口的語義與那些BeanPostProcessor類似,但有一個(gè)主要的不同:BeanFactoryPostProcessor可以操作配置元數(shù)據(jù);也就是說,Spring IoC容器允許在容器實(shí)例化除了BeanFactoryPostProcessor之外的任何beans之前,BeanFactoryPostProcessor讀取配置元數(shù)據(jù)并可能修改它們。
You can configure multiple BeanFactoryPostProcessors, and you can control the order in which these BeanFactoryPostProcessors execute by setting the order property. However, you can only set this property if the BeanFactoryPostProcessor implements the Ordered interface. If you write your own BeanFactoryPostProcessor, you should consider implementing the Ordered interface too. Consult the javadocs of the BeanFactoryPostProcessor and Ordered interfaces for more details.
你可以配置多個(gè)BeanFactoryPostProcessors,你可以通過設(shè)置order屬性來控制這些BeanFactoryPostProcessors的執(zhí)行順序。但是,只有BeanFactoryPostProcessor實(shí)現(xiàn)了Ordered接口時(shí)你才可以設(shè)置這個(gè)屬性。如果你編寫了你自己的BeanFactoryPostProcessor,你也應(yīng)該考慮實(shí)現(xiàn)Ordered接口。關(guān)于BeanFactoryPostProcessor和Ordered的更多細(xì)節(jié)請看文檔。
If you want to change the actual bean instances (i.e., the objects that are created from the configuration metadata), then you instead need to use a
BeanPostProcessor(described above in Section 3.8.1, “Customizing beans using a BeanPostProcessor”). While it is technically possible to work with bean instances within aBeanFactoryPostProcessor(e.g., usingBeanFactory.getBean()), doing so causes premature bean instantiation, violating the standard container lifecycle. This may cause negative side effects such as bypassing bean post processing.
Also,
BeanFactoryPostProcessorsare scoped per-container. This is only relevant if you are using container hierarchies. If you define aBeanFactoryPostProcessorin one container, it will only be applied to the bean definitions in that container. Bean definitions in one container will not be post-processed byBeanFactoryPostProcessorsin another container, even if both containers are part of the same hierarchy.
?
如果你想改變真正的bean實(shí)例(例如,從配置元數(shù)據(jù)中創(chuàng)建的對象),你應(yīng)該需要使用
BeanPostProcessor(3.8.1小節(jié)中描述的)。盡管在BeanFactoryPostProcessor中處理bean實(shí)例在技術(shù)上是可能的(例如使用BeanFactory.getBean()),但這樣做會引起過早的bean實(shí)例化,違背標(biāo)準(zhǔn)的容器生命周期。這可能會產(chǎn)生負(fù)面影響例如繞過bean后處理。
BeanFactoryPostProcessors的作用域也是在每個(gè)容器中。這僅對于容器分層而言。如果在一個(gè)容器中你定義了一個(gè)BeanFactoryPostProcessor,它將適用于那個(gè)容器中的bean定義。一個(gè)容器中的bean定義不能被另一個(gè)容器中的BeanFactoryPostProcessors進(jìn)行后處理,即使兩個(gè)容器是在同一個(gè)分層中。
A bean factory post-processor is executed automatically when it is declared inside an ApplicationContext, in order to apply changes to the configuration metadata that define the container. Spring includes a number of predefined bean factory post-processors, such as PropertyOverrideConfigurer and PropertyPlaceholderConfigurer. A custom BeanFactoryPostProcessor can also be used, for example, to register custom property editors.
為了修改定義在容器中的配置元數(shù)據(jù),當(dāng)一個(gè)bean工廠后處理器在ApplicationContext中聲明時(shí),它會自動執(zhí)行。Spring包含許多預(yù)先定義的bean工廠后處理器,例如PropertyOverrideConfigurer和PropertyPlaceholderConfigurer。定制的BeanFactoryPostProcessor也可以使用,例如,為了注冊定制的屬性編輯器。
An ApplicationContext automatically detects any beans that are deployed into it that implement the BeanFactoryPostProcessor interface. It uses these beans as bean factory post-processors, at the appropriate time. You can deploy these post-processor beans as you would any other bean.
ApplicationContext會自動檢測任何部署在它之內(nèi)的實(shí)現(xiàn)了BeanFactoryPostProcessor接口的bean。在合適的時(shí)間,它會使用這些beans作為bean工廠后處理器。你可以像任何你使用的bean那樣部署這些后處理器beans。
As with
BeanPostProcessors, you typically do not want to configureBeanFactoryPostProcessorsfor lazy initialization. If no other bean references aBean(Factory)PostProcessor, that post-processor will not get instantiated at all. Thus, marking it for lazy initialization will be ignored, and theBean(Factory)PostProcessorwill be instantiated eagerly even if you set the default-lazy-init attribute totrueon the declaration of your<beans/>element.
?
關(guān)于
BeanPostProcessors, 通常情況下你不想配置BeanFactoryPostProcessors為延遲初始化。 如果沒有別的bean引用Bean(Factory)PostProcessor,后處理器將不會實(shí)例化。因此,對它進(jìn)行延遲初始化會被忽略,即使你將<beans/>元素中的default-lazy-init特性設(shè)置為true,Bean(Factory)PostProcessor也會急切的初始化。
Example: the Class name substitution PropertyPlaceholderConfigurer
You use the PropertyPlaceholderConfigurer to externalize property values from a bean definition in a separate file using the standard Java Properties format. Doing so enables the person deploying an application to customize environment-specific properties such as database URLs and passwords, without the complexity or risk of modifying the main XML definition file or files for the container.
你可以使用PropertyPlaceholderConfigurer讀取單獨(dú)文件中的bean定義來使屬性具體化,這個(gè)單獨(dú)文件使用標(biāo)準(zhǔn)的Java Properties格式。這樣做可以在部署應(yīng)用時(shí)定制特定環(huán)境屬性例如數(shù)據(jù)庫URLs和密碼,沒有復(fù)雜性或修改主XML定義文件及容器相關(guān)文件的風(fēng)險(xiǎn)。
Consider the following XML-based configuration metadata fragment, where a DataSource with placeholder values is defined. The example shows properties configured from an external Properties file. At runtime, a PropertyPlaceholderConfigurer is applied to the metadata that will replace some properties of the DataSource. The values to replace are specified as placeholders of the form ${property-name} which follows the Ant/log4j/JSP EL style.
考慮一下下面的基于XML定義的配置元數(shù)據(jù)片段,其中定義了一個(gè)帶有占位符的DataSource。這個(gè)例子展示了從外部Properties文件進(jìn)行屬性配置。在運(yùn)行時(shí),PropertyPlaceholderConfigurer會應(yīng)用到元數(shù)據(jù)中,將會替換DataSource中的一些屬性。通過${property-name}形式的占位符指定要替換的值,這遵循了Ant/log4j/JSP EL風(fēng)格。
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:com/foo/jdbc.properties"/>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
The actual values come from another file in the standard Java Properties format:
真正的屬性值來自于另一個(gè)以標(biāo)準(zhǔn)Java Properties形式編寫的文件:
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
Therefore, the string ${jdbc.username} is replaced at runtime with the value 'sa', and the same applies for other placeholder values that match keys in the properties file. The PropertyPlaceholderConfigurer checks for placeholders in most properties and attributes of a bean definition. Furthermore, the placeholder prefix and suffix can be customized.
因此,在運(yùn)行是字符串${jdbc.username}被替換為sa,其它的匹配屬性文件中的key的占位符的值以同樣方式替換。PropertyPlaceholderConfigurer會檢查bean中大多數(shù)屬性和特性的占位符。此外,占位符的前綴和后綴都可以定制。
With the context namespace introduced in Spring 2.5, it is possible to configure property placeholders with a dedicated configuration element. One or more locations can be provided as a comma-separated list in the location attribute.
Spring 2.5中引入了上下文命名空間,可以通過專用配置元素配置屬性占位符。在location特性可以提供一個(gè)或多個(gè)位置,多個(gè)位置用逗號分開。
<context:property-placeholder location="classpath:com/foo/jdbc.properties"/>
The PropertyPlaceholderConfigurer not only looks for properties in the Properties file you specify. By default it also checks against the Java System properties if it cannot find a property in the specified properties files. You can customize this behavior by setting the systemPropertiesMode property of the configurer with one of the following three supported integer values:
never (0): Never check system properties
fallback (1): Check system properties if not resolvable in the specified properties files. This is the default.
override (2): Check system properties first, before trying the specified properties files. This allows system properties to override any other property source.
PropertyPlaceholderConfigurer不僅僅查找指定Properties文件中的屬性。默認(rèn)情況下,如果不能在指定屬性文件中找到屬性,它也檢查Java System屬性。你可以通過下面三個(gè)支持的整數(shù)值中的一個(gè)設(shè)置配置器的systemPropertiesMode屬性,從而定制查找行為。
never (0): 從不檢查
system屬性fallback (1): 如果不能在指定文件中解析屬性,檢查
system屬性,這是默認(rèn)值。override (2): 在查找指定文件之前,首先檢查
system屬性,這可以使系統(tǒng)屬性覆蓋任何其它屬性源。
Consult the PropertyPlaceholderConfigurer javadocs for more information.
更多信息請看PropertyPlaceholderConfigurer文檔。
You can use the
PropertyPlaceholderConfigurerto substitute class names, which is sometimes useful when you have to pick a particular implementation class at runtime. For example:
你可以
PropertyPlaceholderConfigurer替換類名,有時(shí)候非常有用,特別是運(yùn)行時(shí)你必須選擇一個(gè)特別的實(shí)現(xiàn)類的情況下。例如:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/foo/strategy.properties</value>
</property>
<property name="properties">
<value>custom.strategy.class=com.foo.DefaultStrategy</value>
</property>
</bean>
<bean id="serviceStrategy" class="${custom.strategy.class}"/>
If the class cannot be resolved at runtime to a valid class, resolution of the bean fails when it is about to be created, which is during the
preInstantiateSingletons()phase of anApplicationContextfor a non-lazy-init bean.
如果這個(gè)類不能在運(yùn)行時(shí)解析成一個(gè)有效類,對于一個(gè)非懶惰初始化的bean,當(dāng)它要創(chuàng)建時(shí),在
ApplicationContext的preInstantiateSingletons()期間,bean會解析失敗。
Example: the PropertyOverrideConfigurer
The PropertyOverrideConfigurer, another bean factory post-processor, resembles the PropertyPlaceholderConfigurer, but unlike the latter, the original definitions can have default values or no values at all for bean properties. If an overriding Properties file does not have an entry for a certain bean property, the default context definition is used.
PropertyOverrideConfigurer,另一個(gè)bean工廠后處理器,類似于PropertyPlaceholderConfigurer,但不像后者,最初的定義可以有默認(rèn)值或bean屬性一點(diǎn)也沒有值。如果一個(gè)覆寫的Properties文件對于某個(gè)bean屬性沒有任何輸入,會使用默認(rèn)的上下文定義。
Note that the bean definition is not aware of being overridden, so it is not immediately obvious from the XML definition file that the override configurer is being used. In case of multiple PropertyOverrideConfigurer instances that define different values for the same bean property, the last one wins, due to the overriding mechanism.
注意bean定義沒有意識到被覆寫了,因此從XML定義文件中它不能立刻很明顯的看出在使用覆寫的配置器。為了防止多個(gè)PropertyOverrideConfigurer實(shí)例對于同一個(gè)bean屬性定義不同的值,根據(jù)覆寫機(jī)制,使用最后一個(gè)定義的值。
Properties file configuration lines take this format:
屬性文件配置形式如下:
beanName.property=value
For example:
例如:
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql:mydb
This example file can be used with a container definition that contains a bean called dataSource, which has driver and url properties.
例子文件可以被包含名為dataSource bean的容器定義使用,它有一個(gè)driver和url屬性。
Compound property names are also supported, as long as every component of the path except the final property being overridden is already non-null (presumably initialized by the constructors). In this example…?
混合屬性命名也支持,除了最后被覆寫的屬性,只要路徑的每部分都已經(jīng)是非空(假設(shè)構(gòu)造函數(shù)進(jìn)行初始化)。在這個(gè)例子中:
foo.fred.bob.sammy=123
the sammy property of the bob property of the fred property of the foo bean is set to the scalar value 123.
foo bean中的fred屬性的bob屬性的sammy屬性設(shè)為標(biāo)量值123。
Specified override values are always literal values; they are not translated into bean references. This convention also applies when the original value in the XML bean definition specifies a bean reference.
?
指定的覆寫值總是字面值;它們不能轉(zhuǎn)成bean引用。當(dāng)XML bean定義中的初始值指定了一個(gè)bean引用時(shí),這個(gè)規(guī)范同樣有效。
With the context namespace introduced in Spring 2.5, it is possible to configure property overriding with a dedicated configuration element:
Spring 2.5引入了上下文命名空間,可以用專用配置元素配置屬性覆寫:
<context:property-override location="classpath:override.properties"/>
3.8.3 Customizing instantiation logic with a FactoryBean
Implement the org.springframework.beans.factory.FactoryBean interface for objects that are themselves factories.
為對象實(shí)現(xiàn)org.springframework.beans.factory.FactoryBean接口的是工廠本身。
The FactoryBean interface is a point of pluggability into the Spring IoC container’s instantiation logic. If you have complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML, you can create your own FactoryBean, write the complex initialization inside that class, and then plug your custom FactoryBean into the container.
FactoryBean接口是Spring IoC的實(shí)例化邏輯可插入性的一個(gè)點(diǎn)。如果你有復(fù)雜的初始化代碼,相比于大量的冗余的XML代碼用Java語言來表達(dá)會更好,那么你可以創(chuàng)建你自己的FactoryBean,在類里面編寫復(fù)雜的初始化邏輯,并將你定制的FactoryBean插入到容器中。
The FactoryBean interface provides three methods:
Object getObject(): returns an instance of the object this factory creates. The instance can possibly be shared, depending on whether this factory returns singletons or prototypes.boolean isSingleton(): returns true if this FactoryBean returns singletons, false otherwise.Class getObjectType(): returns the object type returned by the getObject() method or null if the type is not known in advance.
FactoryBean接口提供了三個(gè)方法:
Object getObject(): 返回一個(gè)工廠創(chuàng)建的對象實(shí)例。這個(gè)實(shí)例可能被共享, 依賴于工廠是否返回一個(gè)單例或原型。boolean isSingleton(): 如果FactoryBean返回單例,返回true,否則返回false。Class getObjectType(): 返回getObject()方法返回的類型,如果類型不能提前知道則返回null。
The FactoryBean concept and interface is used in a number of places within the Spring Framework; more than 50 implementations of the FactoryBean interface ship with Spring itself.
FactoryBean的概念和接口在Spring框架中的許多地方都使用了;Spring本身中有不止50個(gè)FactoryBean接口的實(shí)現(xiàn)。
When you need to ask a container for an actual FactoryBean instance itself instead of the bean it produces, preface the bean’s id with the ampersand symbol (&) when calling the getBean() method of the ApplicationContext. So for a given FactoryBean with an id of myBean, invoking getBean("myBean") on the container returns the product of the FactoryBean; whereas, invoking getBean("&myBean") returns the FactoryBean instance itself.
當(dāng)你需要向容器請求一個(gè)真正的FactoryBean實(shí)例本身來代替它產(chǎn)生的bean時(shí),調(diào)用ApplicationContext的getBean()方法時(shí),bean的id前面要加上一個(gè)$符。因此給定一個(gè)id為myBean的FactoryBean,在容器中調(diào)用getBean("myBean"),返回FactoryBean的產(chǎn)品,但調(diào)用getBean("&myBean")會返回FactoryBean實(shí)例本身。