3.1. Introduction In Spring, two most basic and most important packages are: org.springframework.beans and org.springframework.context packages. The code in these two packages provides the foundation for the reverse control characteristics of Spring (also called dependency injections). Beanfactory [http://www.springframework.org/docs/api/org/ SpringFramework / Beans / Factory / BeanFactory.html] provides advanced configuration mechanisms that manage any kind beans (objects), potentially using any one Storage device. ApplicationContext is built on BeanFactory and adds other features. For example, the Spring AOP feature is easier to integrate, information resource processing (for international), event propagation, declarative mechanisms are used to create ApplicationContext and optional parents, and Application layer-related context (such as WebApplicationContext), and other enhancements. In short, BeanFactory provides configuring frameworks and basic features, and ApplicationContext adds stronger features to it, some of these features may be more J2EE and Enterprise Center (Enterprise-Centric). In general, ApplicationContext is a complete super-collection of BeanFactory, any description of any BeanFactory function and behavior is also considered to apply to ApplicationContext. Users sometimes do not determine BeanFactory and ApplicationContext which one is more suitable for use under specific occasions. Usually, most applications built in the J2EE environment is to use ApplicationContext, because it not only provides all the features of BeanFactory and its own additional features, but also provides more declarative methods to use some features, which is usually Satisfactory. You'd better choose BeanFactory's primary scene usually when memory usage is the most important focus (such as in an applet to be calculated every KB), and you don't need ApplicationContext all characteristics. This chapter is roughly divided into two parts, and the first part includes the basic principles applicable to BeanFactory and ApplicationContext. The second part will include only some of the features that apply to ApplicationContext. 3.2. BeanFactory and Bean Definition (Basis) 3.2.1. BeanFactoryBeanFactory is actually instantiated, configuring and managing containers of many beans. These beans are usually cooperated with each other, so they also have dependencies. These dependencies are reflected in the configuration data used by BeanFactory (some dependence may not be as visible as configuring data, and more likely to interact between the running period as the program of the BEAN). A beanfactory is indicated by interface org.springframework.beans.Factory.BeanFactory, which has multiple implementations. The most commonly used simple BeanFactory implementation is org.springframework.beans.factory.xml.xmlbeanfactory. (This has the following suggestions: ApplicationContext is the subclass of BeanFactory, so most users prefer to use ApplicationContext XML form).
Although for most scenes, almost all user code managed by BeanFactory does not need to know BeanFactory, but BeanFactory has to instantiate. This step may occur by a clear user code: InputStream is = new FileInputStream ( "beans.xml"); XmlBeanFactory factory = new XmlBeanFactory (is); or: ClassPathResource res = new ClassPathResource ( "beans.xml"); XmlBeanFactory factory = new XmlBeanFactory (res); or: ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext (new String [] { "applicationContext.xml", "applicationContext-part2.xml"}); // of course, an applicationContext is just a BeanFactoryBeanFactory factory = ( BeanFactory) AppContext; For a lot of application scenarios, user code does not need to instantiate BeanFactory because the Spring Framework code will do this. For example, the Web layer provides support code to automatically read a Spring ApplicationContext and the reading process as part of a J2EE web application startup process. This declarative process is described here: programming BeanFactory will be accepted later, and the following sections describe the configuration of BeanFactory. At the most basic level, a BeanFactory configuration consists of a definition of a bean that must be managed by one or more beanfactory. In an XMLBeanFactory, one or more
XML Version = "1.0" encoding = "UTF-8"?>
(As for the type of bean returned by the static factory method, it is not important to the same class or completely different classes. 3.2.3.1. Creating a Bean by constructing Beans When you use a constructor, all ordinary classes can be used by Spring and Spring compatible with Spring. That is to say, the class created does not need to implement any specified interface or in accordance with a specific style. Just specifying the class of beans is sufficient. However, since you rely on the IOC type you use to specific beans, you may need a default (empty) constructor. In addition, BeanFactory is not limited to managing true javabeans, in fact it can also manage any classes you want to help you manage. Although many people using Spring like to use real JavaBeans in BeanFactory (only one default (non-parameter) constructor, including the appropriate correspondence setter and getter after the properties, but in your beanfactory can also Use special non-Bean style classes. For example, if you need to use a legacy connection pool that is not complying with the JavaBean specification, don't worry, Spring can also manage it. Using XMLBeanFactory, you can make your bean class:
In the following example, two beans are defined as Singleton and the other is defined as Non-Singleton (Prototype). EXAMPLEBean is created while requesting it to BeanFactory each time, and YETANOTHEREXAMPLE is only created; the reference to this instance will be returned during each request.
(In fact, it also supports some setter-based dependent injections after some dependence, which has been injected by constructive function. The dependent configuration is in the form of beandefinition, and it is used with JavaBeans's PropertyEditors to learn how to convert Properties from one format to another. The value of true transmission is changed to the form of the PropertyValue object. However, most Spring users do not handle these classes directly (such as programming), and more use an XML definition file, this file is converted to these Classes instances, used to read the entire BeanFactory Or ApplicationContext. Bean-dependent decision usually follows: l BeanFactory is created and instantiated by using a configuration that describes all Beans. Most Spring users use a BeanFactory or ApplicationContext variant that supports XML format profiles. l The dependence of each bean is in the form of a property, the form of constructing function parameters, or the parameters of the factory method when using a static factory method. These dependencies will be provided to beans after the Bean is really created. l Each attribute or constructor parameter is either a true definition of a value to be set, or a reference to other beans in BeanFactory. In the case of ApplicationContext, this reference can point to Bean in a father applicationContext. l Each is a real value attribute or constructive function parameter, must be able to convert from the format specified by the (profile) to the real type of the attribute or constructive function parameters. The default Spring can convert a string format to all built-in types, such as int, long, string, boolean, and more. In addition, when XML-based BeanFactory variants (including ApplicationContext variants) have provided intrinsic support for definition lists, MAPs, SETS, and Properties collection types. In addition, Spring can convert string values to other types by using JavaBeans's PropertyEditor definition. (You can provide your own PropertyEditor definition to be able to transform your own customized type; more information about PropertyEditors and how to manually add custom Propertyeditors, please refer to Section 3.9, register additional custom PropertyEditors. When a bean property is a Java class type, Spring allows you to use this Class's name as the value of this property, Classeditor This built-in PropertyEditor will help you transform the Class's name into a real Class instance. l It is important to understand: Srping is to verify the configuration of each bean in BeanFactory when creating beanfactory. These checks include the attributes referenced as a bean must actually reference a legitimate Beans (such as referenced beans are also defined in BeanFactory, or when ApplicationContext is in the father context). However, the bean property itself is only set until the bean is established. For beans that are Singleton and set to Pre-Instantiated (Singleton bean in an applicationContext), bean creates when BeanFactory is created, but for other situations, when the bean is requested.
When a bean must be created, it will potentially lead to a series of other beans created, such as its dependence and its dependence (so) is created and assigned. L usually you can trust Spring to do the right thing. It will check when it is loaded in BeanFactory, including reference to the reference and cyclic references that do not exist. It will really set properties and resolve dependence as soon as possible (such as creating those required dependencies), when Bean is really created. This means that even if a beanfactory is loaded correctly, when you ask a bean, if you create the bean or its dependence, this beanfactory will generate an exception. For example, if a bean throws an exception as a result of lack or illegal attributes, this will happen. This potentially postponed some configuration error visibility is the reason for ApplicationContext default pre-unconventional Singleton Beans. Taking them with the previous time and memory for the Beans really needed to create them before ApplicationContext creation, finding a configuration error, not after it. If you like, you can also override this default behavior, setting these Singleton Beans to Lazy-Load (not predeformated). Some examples: First, an use of beanfactory and SETTER-based dependencies. Below is a small part of the XMLBeanFactory configuration file that defines some beans. Next is the official main bean code, demonstrate the appropriate setter declaration.
public class ExampleBean {private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public void setBeanOne (AnotherBean beanOne) {this.beanOne = beanOne;} public void setBeanTwo (YetAnotherBean beanTwo) {this.beanTwo = beanTwo;} public void setIntegerProperty ( INT i) {this.i = i;}} As you can see, setter is declared corresponding to the attribute specified in the XML file. (Attributes in the XML file, directly corresponding to the PropertyValues object in rootbeandefinity) is then a BeanFactory using IOC TYPE3 (dependent-dependent-dependent injection based on constructor). Below is a parameter in the XML configuration, specifying constructor parameters and code display constructor:
public class ExampleBean {private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean (AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {this.beanOne = anotherBean; this.beanTwo = yetAnotherBean; this.i = i;}} As What you see, the constructor parameters specified in the bean definition will be incorporated as the constructor parameters of the ExampleBean. Now consider replacing variants that replace the constructor, Spring is told to call a static factory method to return an example of an object:
(Bean | REF | IDREF | LIST | SET | MAP | PROPS | VALUE | NULL) The bean element in the Property element is used to define an inline bean, replacing the application of the bean defined in BeanFactory elsewhere. Inline BEAN definitions do not require any ID definitions.
A way to solve this problem is to give up some reverse control. BEAN A can be used to request new Bean B instances to the container when needed by implementing BeanFactoryAware knows the presence of the container (see here), using programming means (see here). Because the BEAN code knows Spring and coupled to Spring, this is usually not a good solution. BeanFactory's advanced features: Method Injection can handle this scene in a clean manner and some other scenes. 3.3.3.1. Lookup method Injection Lookup method Injection Using the capacity of the container override the abstraction or specific method of the BEAN in the container, returns the result of the lookup of other beans in the container. The founded bean is usually a Non-Singleton Bean in the scenarius described above (although it can be a Singleton). Spring Implements the Scenario Requirements by modifying binary code on the client's class using the CGLib library. In the client's class, the method definition must be an abstraction (specific) definition of the method: protected abstract singleshothelper createnessLeshotHelper (); if the method is not abstract, Spring will directly rewrite the existing implementation. In the case of XMLBeanFactory, you can use the look-method attribute in the bean definition to indicate Spring to the injection / rewriting method to return a specific bean from the container. for example:
These dependence either is the properties of the BEAN's JavaBean, and there is no one to set the true value in the definition of the bean, or it is provided by the automatic assembly characteristics. This feature is useful when you want to make sure all properties (or all properties of a particular type) are set to the bean. Of course, in many cases, many attributes of a bean class will have default values, or some attributes cannot be applied to all application scenarios, then this feature is limited. Dependency can be applied to each bean application or cancellation, just like an automatic assembly function. The default is to do not check dependencies. Dependency check can be processed in several different modes. In XMLBeanFactory, this is specified by the Dependency-check attribute in the bean definition, this property has the following values: Table 3.3. Relying on the inspection mode mode Unlike NONE does not perform dependencies. The bean property without the specified value is simply not set. Simple depends on the basic type and collection (all things except for the collaborator [such as what to bean], it is in place. Object relies on the partner. All of ALL is based on collaborators, basic types, and collection. 3.4. Customize the natural characteristics of the bean 3.4.1. The lifecycle interface Spring provides some sign interfaces to change the behavior of Bean in BeanFactory. They include InitailizingBean and DisposableBean. Implementing these interfaces will cause BeanFactory to call the previous AfterPropertiesset (), call the latter Destroy (), so that Bean can do some specific actions after initialization and destructuring. Internally, Spring uses BeanPostProcessors to process the flag interface it can find and call the appropriate method. If you need a custom feature or other Spring does not provide lifecycle behavior, you can implement your own beanpostProcessor. About more content this area can be seen here: 3.7 knots, custom Bean with beanpostprocessors. The logo interface of all life cycles is described below. In the appendix's section, you can find the corresponding map, show how Spring manages beans; how the characteristics of the lifecycle change your BEAN's natural features and how they are managed. 3.4.1.1. InitializingBean / Initialization Method Implementation ORG.SPRINGFRAMEWORK.Beans.Factory.InitializingBean interface allows a bean to perform initialization work after all of its necessary properties are set by BeanFactory.
InitializingBean interfaces only developed a method: * Invoked by a BeanFactory after it has set all bean properties supplied * (and satisfied BeanFactoryAware and ApplicationContextAware) *
This method allows the bean instance to perform initialization only * possible when all bean properties. have been set and to throw an * exception in the event of misconfiguration * @throws Exception in the event of misconfiguration (such * as failure to set an essential property) or if initialization fails * / void afterPropertiesSet () throws Exception;.. Note : Usually the use of initializingbean interfaces is to avoid (and do not encourage, because there is no need to couple the code as Spring). The definition of beans supports the specified normal initialization method. Under the occasion of XMLBeanFactory, you can be done by the init-method attribute. For example, the following definition:
Public Class ExampleBean {public void init () {// do some initialization work}} is exactly the same below, but does not couple the code to Spring:
Invoked after population of normal bean properties but before an init * callback like InitializingBean's afterPropertiesSet or a custom init-method. * @param beanFactory owning beanFactory (may not be null) * The bean can immediately call methods on the factory * @throws BeansException in case of initialization errors * @see BeanInitializationException * / void setBeanFactory (beanFactory beanFactory) throws BeansException;..} this program may allow the beans Create their beanfactory directly using the org.springframework.beans.Factory.BeanFactory interface, can also be used directly to obtain more functions. This feature is mainly used to program other Beans. Although this feature is useful in some scenarios, it should be avoided because it allows code to be coupled with Spring, and does not follow the reverse control style (the partner is provided to Beans) .
3.4.2.2. BeanNameaWare If a bean implements the org.springframework.beans.factory.beannameawa interface, and is deployed into a beanfactory, BeanFactory will call bean to inform this bean it (bean) is deployed. This callback occurs after the normal bean property settings, initialization, such as an instildPropertiesset method (or custom Init-method) call, such as the InitializationGbean. 3.4.3. FactoryBean interface org.springframework.beans.Factory.FactoryBean will be implemented by yourself is the object of Factory. The BeanFactory interface provides three ways: l ojbect getObject (): Must return an instance of an object created by this factory. This instance can make shares (depending on the fact that this factory is Singleton or prototype). l Boolean Issingleton (): Must return true if Factory returns Singletons, otherwise returns false. l Class getObjectType (): Returns the type of object returned by the getObject () method, or returns NULL if the type is not presented. 3.5. Child Bean Defines a BEAN definition that may contain a large amount of configuration information, including container-related information (such as initialization methods, static factories, etc.) and values for constructive function parameters and attributes. A Child Bean definition is a bean definition that can define inheritance configuration data from a Parent bean. Then it can overwrite some values or add some other needs. Use the parent's bean definition to save a lot of input work. In fact, this is a template form. Use a beanFactory using a beanFactory, Child Bean definition in the programming. Most users never need to use them at this level, in order to configure Bean definitions in XMLBeanFactory. In an XMLBeanFactory bean definition, use the Parent property to indicate a child bean definition, and the Parent Bean is the value of this property.
The BeanFactory interface only provides five methods for clients: l Boolean ContainSbean (String): Returns Truel Object GetBean (String) if BeanFactory contains a bean definition that matches the name of the name: Returns a bean registered with your name Example. An instance of a shared a Singleton is still a newly created instance, depending on how the bean is configured in the BeanFactory configuration. A beanexception will throw in both cases: Bean is not found (in this case, there is no NosuchbeandefinitionException), or an abnormally l Object GetBean (String, Class) when instantiated and preparing Bean : Returns a Bean registered with a given name. The returned bean will be stitched into a given Class. If the bean cannot be transformed, the corresponding exception will be thrown (BeanNotofrequiredTypeException). In addition, all rules of GetBean (see above) l Boolean Issingleton (String): Bean definitions registered at a given name are a Singleton or a prototype. If the bean definition corresponding to a given name is not found, an exception (NosuchBeandefinitionException) l string [] getaliases (String): If a given bean name has an alias in the bean definition, return these alias 3.6. 1. Get a FactoryBean instead of its product. Some we need to request an actual FactoryBean instance itself to BeanFactory, not the bean it produces. This will do this when you call BeanFactory (including ApplicationContext), add a "&" symbol in front of the incoming parameter bean ID. So, for a given ID for MyBean's FactoryBean, calling GetBean ("MyBean") on BeanFactory will return to FactoryBean's products, and the getBean ("& mybean") will return this FactoryBean instance itself. 3.7. Customization of Bean's Bean Post-Processor is a class that implements org.springframework.beans.factory.config. BeanpostProcessor, with two callback methods. When such a class is registered as a BeanFactory's Post-Processor, each bean instance created by this BeanFactory is called before and after any initialization method (afterPropertiesset and the declared init method), Post-Processor will be from BeanFactory. Get a callback. Post-Processor can freely do what it wants to do, including this callback, including this bean. A bean post-processor is usually used to check the tag interface, or do something such as packaging a bean into a proxy. Some spring assistants are achieved as bean post-processor. It is important to know that BeanFactory and ApplicationContext have a little different.
An ApplicationContext will automatically monitor the bean that implements the BeanPostProcessor interface above it, and registering them as a Post-Processor, and Factory will properly call them when Bean created. There is no difference between deploying a Post-Processor with a different part of the other. On the other hand, when using ordinary beanfactory, Bean Post-Processor must be manually displayed by the following code: ConfigurableBeanFactory Bf = new .....; // Create BeanFactory ... // NOW register some beans // now register any needed BeanPostProcessorsMyBeanPostProcessor pp = new MyBeanPostProcessor (); bf.addBeanPostProcessor (pp); // now start using the factory ... because manual registration is not very convenient, and is an extension of the ApplicationContext BeanFactory function, So it usually recommends that it is best to use the APPLICATIONCONTEXT in Post-Processor. 3.8. Customization Bean Factory POST-Processor is a class that implements org.springframework.beans.factory.config. BeanFactoryPostProcessor interface. It will be manually executed (when BeanFactory) or automatic execution (when ApplicationContext) constructs a change in the entire beanfactory change after the BeanFactory constructed. Spring contains a lot of existing Bean Factory Post-Processor, such as PopertyResourceConfigure and PropertyPlaceHolderConfigurer (which will be described below), and BeanNameAutoproxyCreator (other BEAN transaction packaging or packaging with other proxy will be described later). BeanFactoryPostProcessor can also be used to add custom Editor (see Section 4.3.2, "Built-in PropertyEditors, Conversion Types").
In BeanFactory using BeanFactoryPostProcessor is manual, it would be similar to the following: XmlBeanFactory factory = new XmlBeanFactory (new FileSystemResource ( "beans.xml")); // create placeholderconfigurer to bring in some property // values from a Properties filePropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer (); cfg.setLocation (new FileSystemResource ( "jdbc.properties")); // now actually do the replacementcfg.postProcessBeanFactory (factory); ApplicationContext will be deployed to monitor its implementation on a bean BeanFactoryPostProcessor interface, then Use them as a bean factory post-processor when appropriate. There is no difference between deploying these Post-Processor and deploying other Beans. Because this manual step is inconvenient, and ApplicationContext is the function extension of BeanFactory, so it is recommended to use the APPLICATIONCONTEXT variant when you need to use Bean Factory Post-Processor. 3.8.1. PopertyPlaceHolderConfigurerPorPorPorPlaceHolderConfigure is implemented as a bean factory post-Processor, which can be used to place the property value in the BeanFactory definition to another separate Java Properties format file. This will enable the user to make a complex and dangerous modifications to the primary XML definition file of BeanFactory, you can customize some basic properties (such as the URLs, User Names and Passwords of the Database, User Name, and Password). Consider a segment defined by beanfactory, the DataSource and the PlaceHolder value are defined below: In the following example, a DataSource is defined and we will configure some relevant properties in an external Porperties file. At runtime, we provide a PorPlaceHolderConfigure for BeanFactory, which will replace some properties of DataSource:
3.8.2. PORPERTYOVERRIDECONFIGURER Another Bean Factory Post-Processor: PropertyOverrIDeconfigurer is similar to PropertyPlaceHolderConfiguer, but compared to the latter, the former definitions can have default values or no values at all for Bean properties. If a relatively important Properties file does not contain an entry corresponding to a bean property, the default context definition will be used. Note: The definition of Bean Factory will not be aware that it is overwritten, so only the XML definition file is not obviously clearly known whether Override Configure is used. When there are multiple PorpertYoverrIDeconfigurer to define different values with a bea property, the last will win (depending on the overlay mechanism). The configuration line of the Properties file should be the following format: beanname.property = Value An example of a Properties file will be the following: DataSource.driverclassName = com.mysql.jdbc.driverDataSource.URL = JDBC: mysql: mydb If a beanfactory Contains a bean called DataSource, this bean has DRIVER and URL properties, then this instance file is available in this beanfactory. 3.9. Registered Additional Customized PropertyEditor When setting the bean property with a string value, BeanFactory essentially uses the standard JavaBeans's PropertyEditor converts these String to the complicated type of properties. Spring has a pre-registered PropertyEditor (for example, converting a character string representation into a real Class object). In addition, if a class's PropertyEditor is properly named and placed in the same package with which it supports, the Java standard JavaBeans PropertyEditor lookup mechanism will automatically find this PropertyEditor. If you need to register other custom PropertyEditor, there are also several mechanisms available here. The most manual method is also usually inconvenient and unbursed, which is a regiGurableBeanFactory interface regiGuRableBeanFactory interface, which is assumed to have a beanFactory reference. Convenient for some mechanisms is to use a special Bean Factory Post-Precessor called CustomeditorConfigurer. Although Bean Factory Post-Processor can be used in manual use of BeanFactory, this one has a nested attribute setting. Therefore, it is highly recommended (as described here), it can be used with ApplicationContxt, so that it can be deployed in other beans and is automatically monitored and applied. 3.10. Profile of ApplicationContext Beans package provides basic features for management and manipulated beans, usually in programming, while the Context package adds ApplicationContext, which enhances the BeanFactory functionality in a more frame-oriented manner. Most users can use ApplicationContext in a fully declarative manner, and even do not create it manually.
However, replacing the support class such as ContextLoader, CONTEXTLOADER automatically launches an ApplicationContext and uses the process as part of the normal launch process of the J2EE web application. Of course, in this case, it can be programmed to create an ApplicationContext. The foundation of the Context package is the ApplicationContext interface, located in the org.springframework.context package. It is derived from BeanFactory to provide all features of BeanFactory. In order to operate in a more frame-oriented manner, the Context package also provides the following: l messageSource, providing access to I18n information to resources access, such as URL and file L event propagation implementation BEANL of the ApplicationListener interface is loaded with multiple (graded) Context, allowing each focus on a specific level, such as the application's Web layer, because ApplicationContext includes all the features of BeanFactory, so it is recommended to use BeanFactory, except for very few Some qualified occasions, such as in an applet, memory consumption is decisive, and several additional KBs produce different results. The next chapter will narrate the features that ApplicationContext adds the basic capabilities of BeanFactory. 3.11. ApplicationContext is the functionality as described above, and ApplicationContext has several distinguishes between BeanFactory features. Let's observe them one by one. 3.11.1. Use the MessagesourceApplicationContext interface to inherit from the Messagesource interface, so information (i18n or international) feature is provided. Working with NestingMessagesource, you can handle information about the level, which is the basic interface of the processing information provided by Spring. Let's browse the methods defined here: l String GetMessage (String Code, Object [] args, string default, local loc): The basic method of obtaining information from Messagesource. If information is found for the specified area, use the default information (parameter default). The passive parameter ARGS is made as a value to be replaced in the information, which is implemented through the MessageFormat of the Java Standard Class Library. l String getMessage (String Code, Object [] args, local loc): Essentially the same, but there is a difference: no default; if the information can't be found, you will throw a NosuchMessageException. l String GetMessage (MessagesourceResolveable Resolvable, Locale Locale): All attributes used above are packaged into a class called MessagesourceResolvable, you can use it directly through this method. When ApplicationContext is loaded, it automatically finds the Messagesource Bean defined in context. This bean must be called Messagesource. If such a bean is found, all calls to the above methods will be entrusted to this found message source.
If you don't find your message source, ApplicationContext will try to check if its Parent contains the bean of this name. If so, it will take the found bean as a messageSource. If it finally does not find any information source, an empty StaticMessagesource will be instantiated, in order to accept requests for the above method. Spring currently provides two Messagesource implementations. They are ResourceBundleMessagesource and StaticMessagesource. Both realize NestingMessagesource to be able to nested information. STATICMESSAGESOURCE is almost unused from Source to Source, in addition to providing programming. ResourceBundleMessageSource some more interesting, we will provide it an example: < Value> format value>
This parameter is an instance of your custom Event Class by calling ApplicationContext () methods and specifying a parameter. Let's take a look at an example. The first is ApplicationContext:
public class EmailBean implements ApplicationContextAware {/ ** the blacklist * / private List blackList; public void setBlackList (List blackList) {this.blackList = blackList;} public void setApplicationContext (ApplicationContext ctx) {this.ctx = ctx;} public void sendEmail (String address, String text) {if (blackList.contains (address)) {BlackListEvent evt = new BlackListEvent (address, text); ctx.publishEvent (evt); return;} // send email}} public class BlackListNotifier implement ApplicationListener {/ ** notification address * / private String notificationAddress; public void setNotificationAddress (String notificationAddress) {this.notificationAddress = notificationAddress;} public void onApplicationEvent (ApplicationEvent evt) {if (evt instanceof BlackListEvent) {// notify appropriate person}}} Of course, this particular example may be implemented in a better way (perhaps With AOP characteristics), but it is still enough to explain the basic event mechanism. 3.11.3. Use resources in Spring Many applications require access to resources. Resources can include files, as well as things such as web pages or NNTP newsfeeds. Spring provides a clear and transparent solution to access resources in a way of an agreement. The ApplicationContext interface contains a method responsible for this job. (GetResource (String) The Resource class defines several methods, which are shared by all Resource implementations: Table 3.5. Resource function method Interpretation GetInputStream () opens an InputStream on the resource and returns this InputStream. EXISTS () Verify the resource time existence, if there is no return false. Isopen () If this resource cannot open multiple streams will return TRUE. For some resources other than file-based resources, they will return FALSE, which cannot be read at the same time. getDescription () Returns the description of the resource, usually a fully qualified or actual URL. Spring provides several resource implementations. They all need a String actual resource location. According to this string, Spring will automatically select the correct resource implementation for you. When requesting a resource to ApplicationContext, Spring first checks the location of the resource you specify and find any prefix.
Depending on the implementation of ApplicationContext, different resource will be available. Resource is preferably configured using ResourceEditor, such as XMLBeanFactory. 3.12. User Behavior BeanFactory in ApplicationContext has provided many mechanisms to control the lifecycle of beans deployed in it (such as flag interface initializingbean or disposablebean, their structure and init-method and destroy-method properties in XMLBeanFactory configuration, as well as Bean Post- Processor is the same. In ApplicationContext, these can also work, but also add some mechanisms for customizing Beans and container behaviors. 3.12.1.ApplicationContextaWare Symbol Interface All BeanFactory can also be used here. ApplicationContext also adds a BEAN that can be implemented: org.springframework.context.ApplicationContextaWare. If a bean implements this interface and deployed in Context, when this bean creates, this interface will use the setApplicationContext () method. Pressing this bean, providing a reference to the current context, which will be stored so that the bean will interact with Context. 3.12.2.BeanPostProcessorBean Post-Processor (implemented org.springframework.beans.factory.config. BeanpostProcessor's Java class has been described above. It is still a referential manner that Post-processor is used in ApplicationContext than the convenient use of the most in the ordinary beanfactory. In an ApplicationContext, a deployment of the above interface The bean will be automatically found and as a bean post-processor is registered, and it is appropriately called when the creation of each bean in Factory is appropriate. 3.12.3.BeanFactoryPostProcessorBean Factory Post-Processor (implemented org.springframework.beans) .factory.config. BeanfactoryPostProcessor interface Java classes have been introduced in front. It is still worth mentioning again, Bean Fa Cty POST-Processor is used in ApplicationContext more convenient than in normal Beanfactory. In an ApplicationContext, a bean that implements the deployment of the above interface will be automatically found and is registered as a bean factory post-processor, which is called when appropriate. 3.12.4. PropertyPlaceHolderConfigurerPropertyPlaceHolderConfigure has been described in BeanFactory. It is still worth mentioning again, it is more convenient to use in ApplicationContext, because when it is deployed like other beans, Context will automatically identify and apply any Bean factory post-processor (of course, including this special) . There is no need to run it in this time.
<-! Property placeholder post-processor ->
public class ExoticTypeEditor extends PropertyEditorSupport {private String format; public void setFormat (String format) {this.format = format;} public void setAsText (String text) {if (! format = null && format.equals ( "upperCase")) { Text = text.touppercase ();} exotictype type = new exotictype (text); setValue (TYPE);}} Finally, we use CustomeditorConfigure to register the new property -Edext, then use this PropertyEditor when needed. :
Which one is using depends on yourself, but if all the conditions are the same, you will probably prefer ContextLoaderListener; more information about compatibility can refer to the CONTEXTLOADERSERVLET Javadoc. You can register an ApplicationContext with the CONTEXTLOADERLISTENER:
Another example, in a multi-layer complex J2EE application (such as a lot of JAR, EJB, and WAR packaging into an EAR), each layer has its own ApplicationContext definition (effectively constitutes a hierarchy), if the top There is only one web-app (war), the better approach is to create a combination ApplicationContext consisting of XML definition files from different layers. All ApplicationContext variants can be constructed in this manner from a plurality of definitions files. However, if there are multiple brother web-apps on the top, create an applicationContext for each web-app, each ApplicationContext contains most of the same underlying bean definition, which will cause problems due to memory use because Creating a number of beans's COPY for a long time (such as Hibernate SessionFactory, and other possible side effects. Alternatively, classes such as ContextSingletonBeanFactoryLocator and SingletonBeanFactoryLocator can be used to load multiple hierarchical (for example, another parent) beanfactory or ApplicationContext when needed, as needed, as a WEB-App ApplicationContext . The result of this is that the bottom bean definition is only loaded while it is required and is only loaded once. 3.16.1. Using SingletonBeanFactoryLocator and ContextSingletonBeanFactoryLocator you can view their respective Javadoc to get detailed usage examples. As mentioned in the EJB chapter, Spring provides the convenient base class provided by EJB generally uses a Non-Singleton's BeanFactoryLocator, which can be replaced by the use of the above two classes when needed. Participate in the forum discussion: http://www.matrix.org.cn/forum.asp More Technical Articles: http://www.matrix.org.cn/Article.aspmatrix Java Portal: http://www.matrix. Org.cn Original Address: http://www.matrix.org.cn/Article/1052.htmlezerg Programming