Spring Reference Chapter 3

xiaoxiao2021-03-06  105

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 elements are configured in top-level elements.

... ... ... 3.2.2. Bean Defines Bean definitions in an XMLBeanFactory entity including the details of the following information: l A className: Typically this is the true implementation class of the bean described in the bean definition. However, if a bean creates in a static factory method rather than being created by the ordinary constructor, then here is actually the classname of the factory class. l Bean behavior Configuration Elements: Declare this bean behavior in the container (such as prototype or singleton, automatic assembly mode, dependent check mode, initialization, and destructive method). l Construct Function parameters and properties to impart new creating beans: Lifting an example, a number of connections used by the BEAN of the management connection pool (ie, as a Property can also be used as a constructor parameter), or the pool size limit number. l This bean requires other Beans: such as its partner (the peer can also be used as a parameter of the attribute or constructor). This is also called dependence. The concept listed above is directly converted to a set of elements that make up the bean definition. These elements are listed in the table below, and there is a link corresponding to each of their more detailed descriptions. chart 3.1. Bean Definition Description Features More Information Class 3.2.3, Bean ClassID and Name 3.2.4, Bean Sign (ID and Name) Singleton or Prototype 3.2.5, use Singleton or not constructor 3.3.1 Section, setting the bean's attributes and collaborators beans 3.3.1, setting the bean's attributes and collaborators Automatic assembly mode 3.3.5, automatic fittings Dependence-dependent inspection mode 3.3.6, check dependency initialization method 3.4.1 Section, lifecycle interface analysis method 3.4.1, lifecycle interface Note Bean definition is represented by true interface org.springframework.beans .factory.configurework.beans .Factory.Config.Beandefinition and its various sub-interfaces and implementations. However, the vast majority of user code does not need to work directly with Beandefination. 3.2.3. The bean classclass property is usually mandatory (see Section 3.2.3.3 - Creating the BEAN and 3.5-CHILD BEAN through the instance factory method) two exceptions), which are used to reach one of the two purposes. In most common scenes, beanfactory directly calls the bean constructor to create a bean (equivalent to the Java code called New), the class property specifies the class of the bean you need to create. In a less common scene, BeanFactory calls a static so-called factory method of a class to create a bean, and the class attribute specifies the class that actually contains static factory methods.

(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: As for the construction method Parameters (optional), and the properties of the instance after the object instance construct will be described later. 3.2.2.2. Creating a bean by static factory approach When you define a bean created using a static factory method, use the Class property to specify a class containing a static factory method. This time you need another property called Factory-Method to specify the name of the factory method. Spring is expected to call this method (including an optional set parameter will be described later) and return a valid object, which is treated as the object created with a constructor. Users can use such beans to call the static factories in the legacy code. Below is an example of a bean definition, declare a bean is created by calling a factory method. Note that the definition does not specify the type of return object, only the class containing the factory method is specified. In this example, CreateInstance must be a static method.

provides the factory method to provide parameters (optional), and the object instance is returned by the factory method, the properties of the instance will be set. Will be described later. 3.2.3.3. Creating beans through instance factories Method is very similar to using a static factory approach, using an instance factory method (non-static), creating a new type by calling an factory method that already exists in the factory (this bean should be factory type) BEAN. To use this mechanism, the class attribute must be empty, and the factory-bean property must specify a name (¥¥) that contains the bean of the factory method. The factory method itself still wants to set up Factory-Method property. Below is an example:

... Setting the bean property will be discussed later, this program has a suggestion that the Factory Bean itself can be contained Manage and configure by relying on injection. 3.2.4. BEAN's flag (ID and NAME) each bean has one or more IDs (also called flag, or names; these nouns are said). These IDs must be unique in BeanFactory or ApplicationContext managed by Bean. A bean is almost only one ID, but if a bean has more than one ID, then the additional substances can be considered an alias. In an XMLBeanFactory (including various forms of ApplicationContext), you can specify the ID (S) of the BEAN with the ID or Name property, and specify at least one ID in these two or one of the properties. The ID attribute allows you to specify an ID, and it is tagged as a true XML element in XML DTD (defined document), so Parser can do some additional checks when other elements refer to it. Because of this, the ID of the BEAN is specified with the id property is a better way. However, the XML specification strictly defines legitimate characters in the XML ID. Usually this is not a real constraint, but if you need to use one of these characters (illegal characters in the id), or you want to introduce other alias for bean, then you can specify one or more by name attributes IDS (with comma "," or semicolon ";" separate). 3.2.5. Use Singleton or not using Beans to be defined as one of two deployment modes: Singleton or Non-Singleton. (The latter kind is also called Prototype, although this noun is not accurate because it is not very suitable). If a bean is Singleton, only one instance of this bean is managed, all IDs or IDS definitions that match this bean definition will cause the unique specific bean instance to be returned. The consequences of BEAN deployment of Non-Singleton, Prototype mode are: Every request for this bean creates a new bean instance. This is ideal for, for example, every USER requires a separate User object. Beans default is deployed as Singleton mode unless you are assigned to be additionally. It is necessary to keep the type of Non-Singletion (Prototype), each time a request for this bean causes a newly created bean and this may not be you really want. So just change the mode to prototype when absolute needs.

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.

Note: When deploying a bean for prototype This bean's life cycle will have a slight change in the life cycle of this bean. By definition, Spring cannot manage the entire lifecycle of a non-singleton / prototype bean, because after it is created, it is handed over to the client and the container will no longer pay attention to it. When talking with Non-Singleton / Prototype Bean, you can imagine the role of Spring as a "new" operator. From then on any life cycle, things are processed by the client. The lifecycle of Bean in BeanFactory will be described in more detail in Section 3.4.1, lifecycle interface section. 3.3. Attributes, collaborators, automatic assembly and dependence inspection 3.3.1. Setting the properties of the bean and the counter-control of the collaborator have been mentioned as dependent injections. This basic rule is that Bean defines their dependence (such as other objects that cooperate with them): the parameters of constructor, the parameters of the factory method; when the object instance is constructed or returned from one factory method At this instance. The work of the container is to create these dependencies after the bean is created. This Is Fundamentally The Inverse (Hence The Name Inversion of Control) of The Bean Instantiating or Locating ITS Dependencies ON ITS OWN Using Direct Construction of Classes is like ServiceLocator mode. We will not explain the advantages of relying on the injection, it is clear that by using it: code is very clear; when Beans is no longer looking for their dependence but is provided by the container, do not even know where to position dependence and dependence What type is, at this time, the high-level decoupling has become very easy. As mentioned above, there are two main forms of reverse control / dependency injection: L Based on the SETER-dependent injection, it is to instantiate your bean after calling a non-argument-free constructor or a no-array-free static factory method. Tune setter implementations on your bean. The use of setter-based injection dependent beans is real JavaBeans in BeanFactory. Spring generally advocates the use of Setter-based dependencies because many constructor parameters will be cumbersome, especially in some cases where some attributes are optional. L is based on the injection dependence of the constructor, which is implemented by calling a constructor with many parameters, each parameter represents a partner or attribute. In addition, calling with a specific parameter static factory method to construct Bean can be considered almost equivalent, the next text will regard the parameters of the constructor and the parameters of the static factory method as the same. Although Spring generally advocates the use of Setter-based dependencies in most cases, Spring still fully supports the dependent injection based on constructor, because you may want to use it in those who only provide multi-parameter constructor and no setter Beans on beans. Also for some relatively simple Beans, some people prefer to use constructor methods to ensure that Beans will not be constructed in the wrong form. BeanFactory also supports these two ways that will depend on injection into the managed bean.

(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. 1

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: 1

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:

1 public class examplebean {... // a private constructor private examplebelet (...) {...} // a static factory method /// THE arguments to this method can be considered the dependencies of the bean that // is returned, regardless of how those arguments are actually used. public static ExampleBean ExampleBean (AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {ExampleBean eb = new ExampleBean (.. .); // Some Other Operations ... Return EB;}} Need to note: static factory methods are supported by constructor-arg elements Hold, constructor is actually the same. These parameters are optional. It is important to be the class type returned by the factory method. It is not necessary to consistent with the Class of a static factory method, although the above example is the same. The example factory method (Non-Static) mentioned above is basically the same (in addition to using the Factory-Bean property instead of the Class property), it will not be described in detail here. 3.3.2. In-depth bean properties and constructive function parameters are as mentioned earlier, the attributes and constructor parameters of the beans can be defined as reference (collaborators) of other Managed Beans, or inline definitions. In order to achieve this, XMLBeanFactory supports many child elements in the Property and Constructor-Arg elements. Value Elements Specify attributes or constructor parameters in the form of human readable strings. As mentioned earlier, JavaBeans's PropertyEditors is used to transform these string values ​​from java.lang.string types into real properties or parameter types.

com.mysql.jdbc.driver jdbc: mysql: // localhost: 3306 / mydb root null elements are used to process NULL values. Spring treats empty parameters such as Porperties as empty strings. Next, this XMLBeanFactory configuration: causes the email attribute to be set to "", with Java code: ExampleBean .semail ("") is equivalent. And dedicated elements can be used to specify a null value, so: with code: ExampleBean . Setemail (NULL) is equivalent. List, SET, MAP, and PROPS elements can be used to define and set the properties and parameters of List, SET, MAP, and Properties of Java.

... The Magic Property The funny property a list element followed by a reason Just Some String Note: The Value of the MAP Entry or SET, and their values ​​can be any of the following elements:

(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. tony 51 < / Property> iDREF element is completely a manner that prevents errors, setting properties with the ID or NAME string of other beans in the container.

This is consistent with the following segment when running:

ThetargetBean The first form is better than the second form: Using the IDREF tag will enable Spring to verify that other beans really exist when deploying; in the second form, The Class of the targetname property will only do its own verification when this Class is instantiated by Spring, which is likely to be a long time after the container is really deployed. In addition, if the referenced bean is in the same XML file and the name of the bean is the ID of the bean, then the local property can be used. It will let XML Parser verify the name of the bean earlier, when XML document parsing.

REF element is the element that is the element that can be used in the Property element. It is used to give some specific attribute settings, which are references to other beans managed by the container (can be called partners). As mentioned above, the referenced bean is considered to be dependent on the bean to be set, and the Bean approved will be required before the property setting (if it is a Singleton BEAN may have been initialized by the container), Once, it is initialized. All references are just a reference to other objects, but the ID / name of other objects here is specified in three forms. These three different forms determine how Scoping and verification are processed. Specifying the target bean is the most common form with the REF tag, for the same beanfactory / applicationContext, or if any bean in the same XML file, or any bean in the Parent BeanFactory / ApplicationContext is allowed to create a bean pointing to it. The value of the bean property can be the same as the ID attribute of the target bean, or any of the name attributes of the target bean. Specifying the target bean with the Local property to verify the XML ID reference in the same file using the ability of XML Parser. The value of the local property must be the same as the id attribute of the target bean. If there is no match in the same file, XML Parser will generate an error. Therefore, if the target bean is in the same XML file, then use local form will be the best choice (in order to find an error as possible). Specifying the target bean allows a reference to the bean in the Parent BeanFactory (ApplicationContext) of the current BeanFactory (ApplicationContext). The value of the Parent property can be the same as the ID attribute of the target bean, or the same value in the Name property of the target bean, and the target bean must be in the current beanFactory (ApplicationContext). When you need to use some proxy to pack a bean existing in a Parent context (possibly with the same name in the Parent), you need the original object to be used to pack it. 3.3.3. Method Injection For most users, most Beans in the container will be Singletons. When a Singleton Bean needs to cooperate with another Singleton Bean (use), or a non-singleton bean needs to work with another non-singleton bean, to deal with this dependency by defining a bean for another bean property. It is enough. However, there is a problem when the life cycle of the bean is different. Think about a Singleton Bean A, perhaps you need to use a Non-Singleton Bean B when you call. The container only creates this Singleton Bean A, so there is only one chance to set its properties. The container does not have a chance to provide the instance of new bean b for Bean A each time.

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:

... When Mybean needs When an instance of a new SingleshotHelper, it will call its own CreateSingLeshotHelper method. It is worth noting that the staff deploys Beans must carefully deploy SingleshotHelper as a Non-Singleton (if it does need this). If it acts as it A Singleton (whether explicitly pointed or default) is deployed, the same SINGLESHOTHELPER instance will be returned each time .lookup method can be combined with the constructor injection (with the created bean to provide an optional constructor parameter), Can be combined with Setter (setting attributes above the created bean). 3.3.3.2. Replacement without the way without a Lookup method Injection, another method of injection is in the form of an injection, with additional methods to replace the managed bean Any method. Users can safely skip this section (narrative this some advanced features) unless this feature does need. In an XMLBeanFactory, for an deployed bean, the replaced-method element can be used The existing method is replaced with other implementations. Consider the following Class, there is a computevalue method we want to rewrite: public class myvaluecalculator {public string computevalue (string infut) {... Some real code} ... Some Other Methods} You need to provide information for new method definitions org.springframework.beans.Factory.support.Methodrep The class of the lacer interface. [Code] / ** meant to be used to override the existing computevalue implementation in MyvalueCalculator * / public class ReplacementComputevalue implements MethodReplacer {public Object reimplement (Object o, Method m, Object [] args) throws Throwable {// get the input value Work with it, and return a computed result string input = (string) args [0]; ... return ...;} [/ code] Deployment Original Class and Specify Method Rewinding BeanFactory Deployment Definition Image Shown of:

<-! Arbitrary method replacement -> String replaced-method element in one or more arg-type elements in the Element is hintted, the method of this method The signature is overloaded. Note that the signature of the parameters is only true when the method is overloaded and there is a plurality of different forms. For convenience, the type string of the parameters can make the list of subscribers. For example, The following matches java.lang.string. Java.lang.string string STR Because the number of parameters is usually different, it is only possible to distinguish possible, so only the shortest string of matching parameters can save a lot of typing work. 3.3.4. Using Depends-On For most cases, a bean is a dependence on other beans, which is set by this bean as a property as other beans. In XMLBeanFactory, it is done by REF elements. Unlike this way, sometimes one knows that Container will only give the ID of its dependencies (using a string value or equivalent IDREF element). The first bean is programmed to the container request Its dependence. In both cases, dependent is properly initialized before relying on its bean. For relatively rare cases, the dependence between Beans is not directly (for example, when a static initial block in a class needs to be triggered For example, database-driven registration), Depends-ON elements can be used to express one or more beans initialization before using this element's bean initialization. The following is an example of a configuration:

3.3.5. Automatic fittings can automatically fit the relationship between beans. This means that Spring automatically gets your bean collaborators (other beans) by checking the content of BeanFactory, which is possible. The automatic assembly function has 5 modes. The automatic assembly is specified to each bean, so you can give some Beans and other Beans do not automatically assemble. Saving significant typing work is possible by using auto assembly, reducing (or eliminating) the needs of the specified property (or constructor parameters). In XMLBeanFactory, use the Autowire property of the bean element to specify the automatic assembly mode defined by the bean. The following is the allowable value: Table 3.2. Automatic assembly mode mode interpretation No automatic assembly. BEAN's reference must be defined by the REF element. This is the default configuration, which does not encourage this configuration in a large deployment environment, because clear designated collaborators can get more control and clarity. To some extent, this is also a document form of the system structure. BYNAME is automatically assembled through the attribute name. This option checks BeanFactory to find a bean that is the same name as the attribute that will be assembled. For example, you have a bean definition to be set to automatically assemble through the name, which contains a master property (that is, it has a setmaster () method), and Spring will find a bean definition called Master, and then use it Set the master property. ByType If BeanFactory is just a bean as the same type of property, it is automatically assembled. If there is more than one situation, a fatal exception will be thrown, it indicates that you may not use the automatic assembly of the BYTYPE. If there is no matching bean, what doesn't happen, and the property will not be set. If this is the situation you don't want (nothing happens), by setting the value of the Dependency-check = "Objects" attribute to throw errors. This constructor is similar to byType, but it is applied to constructive function parameters. If it is not just a bean in BeanFactory, a fatal error is generated by the same type as the constructor parameter. AutodTect By selecting constructor or bytype by province's inside the bean class. If you find a default constructor, you will apply byType. Note: Explicit dependence, such as Property and Construtor-Arg, always overwrite automatic assembly. Automatic assembly behavior can be used in conjunction with dependencies, depending on the check, will occur after the automatic assembly is completed. Note: As we have already mentioned, for large applications, automatic assembly does not encourage because it removes the transparency and structure of your cooperation class. 3.3.6. Check relies on unresolved dependence on bean to deploy BeanFactory, Spring has the ability to check their existence.

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:

public class AnotherExampleBean implements InitializingBean {public void afterPropertiesSet () {// do some initialization work}} 3.4.1.2. DisposableBean / despreading methods Implementing org.springframework.beans.Factory.DisposableBean interface allows a bean to get a callback when it contains its BeanFactory destruction. DisposableBean only specifies a method: / ** * Invoked by a BeanFactory on destruction of a singleton * @throws Exception in case of shutdown errors * Exceptions will get logged but not rethrown to allow * other beans to release their resources too.. . * / Void destroy () THROWS Exception; Note: Usually the use of the DisposableBean interface can be avoided (and it is not encouraged because it is unnecessarily coupled to Spring). The definition of beans supports the specified method. Under the occasion of XMLBeanFactory, it is done through the Destroy-Method property. For example, the following definition: public class examplebean {public void cleanup () {// do some destruction work (Like Closing The same is the same as the definition below, and the code will not be coupled to Spring:

public class AnotherExampleBean implements DisposableBean {public void destroy () {// do some destruction work}} important note: When deploying a bean in portotype time mode, Bean's life cycle will have a little change. By definition, Spring cannot manage the entire lifecycle of a non-singleton / prototype bean, because after it is created, it is handed over to the client and the container will no longer pay attention to it. When talking with Non-Singleton / Prototype Bean, you can imagine the role of Spring as a "new" operator. From then on any life cycle, things are processed by the client. The lifecycle of Bean in BeanFactory will be described in more detail in Section 3.4.1, lifecycle interface section. (This is this section) 3.4.2. Understand who you are 3.4.2.1. BeanFactoryaWare is a class that implements the org.springframework.beans.factory.beanfactoryAware interface, when it is created by beanfactory, it has a reference to the BeanFactory pointing to creating it. public interface BeanFactoryAware {/ ** * Callback that supplies the owning factory to a bean instance. *

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.

Parent 1 Override If the Child Bean definition does not specify a Class, a child bean definition will use the parent definition Class, of course, it can also be overwritten. In the later circumstances, Child Bean's class must be compatible with the Parent Bean, such as it must be able to accept the father's attribute value. A Child Bean definition will inherit constructive function parameters, attribute values, and methods from the father, and selectively add new values. If the initialization method, the destruction method, and / or the static factory method is designated, they will cover the corresponding settings of the father. The remaining settings will always be obtained from sub-definitions: Depends ON, Autowire Mode, Dependency Check, Singleton, Lazy Init. In the example below, the parent definition does not specify a class:

parent 1 override < / Property> This Parent bean can not instantiate itself; it is actually just a pure template or abstract bean, just serial as a child-defined parent definition . To try to use such a Parent bean alone (such as a REF attribute that uses it as other beans, or directly using this Parent BEAN ID, the getBean () method will result in an error. Similarly, the PreInstantiatesingletons method inside the container will completely ignore a bean definition that neither Parent does not have a Class property, as they are incomplete. Important attention: There is no way to explicitly declare a bean as an abstraction. If a bean does have a Class definition, it can be instantiated. And pay attention to XMLBeanFactory default to the existing Singletons by default. So it is very important: if you have a (parent) bean definition specified the class property, and you want to use it as a template, then you must ensure that the lazy-init property is set to true (or mark the bean tag For non-singleton, XMLBeanFactory (and other possible containers) will previse it. 3.6. The BeanFactory interaction beanfactory is essentially the excuse of advanced Factory, which is capable of maintaining different beans and their relying registration. BeanFactory makes you use the bean factory to read and access bean definitions. When you want to use BeanFactory, you can create one as the same as below and read some bean definitions in some XML format: InputStream is = new fileinputstream ("beans.xml"); xmlbeanfactory factory = new xmlbeanfactory (IS); basically that's enough. Use getBean (String) you can get the instance of your bean. If you define it as a Singleton (default) you will get the same bean reference, if you set Singleton to false then you will get a new instance each time. Beanfactory is an amazing simple in the eyes of the client.

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:

$ {jdbc.driverclassname} < / Property> $ {jdbc.url} $ {jdbc.username} < / proty> $ {jdbc.password} The real value comes from another Properties format: jdbc.driverclassname = org. hsqldb.jdbcDriverjdbc.url = jdbc: hsqldb: hsql: // production: 9002jdbc.username = sajdbc.password = root in order to use the BeanFactory, bean factory post-processor must manually run: XmlBeanFactory factory = new XmlBeanFactory (new FileSystemResource ( "beans.xml")); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer (); cfg.setLocation (new FileSystemResource ( "jdbc.properties")); cfg.postProcessBeanFactory (factory); Note, ApplicationContext can automatically identify and deploy applications thereon Realize BeanFactoryPostProcessor's bean. This means that PropertyPlaceHolderConfigure is very convenient when using ApplicationContext. For this reason, it is recommended to use this or other Bean Factory PostProcessor to use ApplicationContext instead of BeanFactroy. PropertyPlaceHolderConfigurer is not only in the Porperties file you specified, if it does not find the properties you want to use, it will check in the Java System Properties. This behavior can be customized by setting the configure's SystemPropertiesMode property. This attribute has three values, one lets configure are always overwritten, one let it cover, one to override it only in the Properties file. Please refer to PropertiesPlaceHolderConfigure to get more information.

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 exception windows This configuration assumes that you have three resource bundle in ClassPath , Called Format, Exceptions, and Windows, respectively. Standard practice using JDK: Processing information through ResourceBundle, requests for any processing information will be processed. TODO: Epew an example 3.11.2. The event processing in the propagation event ApplicationContext is provided through the ApplicationEvent class and the ApplicationListener interface. If a bean that implements the ApplicationListener interface is deployed, the bean will be notified each time an ApplicationEvent is released. Essentially, this is a standard OBServer design pattern. Spring provides three standard events: Table 3.4. Built-in event event interpretation ContextRefreeshedEvent When ApplicationContext has instantiated or refreshed events. Here, all beans are loaded, Singleton is predefined, and ApplicationContext is ready to use ContextClosedEvent to end the event when the CLOSE () method using ApplicationContext is incnoated. The end of this means that: Singleton is destroyed with a Web-related event, telling all the BEAN an HTTP request has been responded (this event will be released after a request). Note that this event can only be applied to Wen applications that use Spring DispatcherServlets. You can also achieve custom events.

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: black@list.org white@list.org john@doe.org spam@list.org then actual bean:

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 -> jdbc.properties < /Value (/Property "(/Bean 3.13). Sign up for additional custom PropertyEditor As mentioned earlier, Spring uses standard JavaBeans PropertyEditor to convert the properties value represented by the string into the real complex type of the properties. CustomeditorConfigure (a special bean factory post-processor) allows ApplicationContext to easily add support for additional PropertyEditor. Consider a user class ExoticType, and other properties as required ExoticType DependsOnExotic class: public class ExoticType {private String name; public ExoticType (String name) {this.name = name;}} public class DependsOnExoticType {private ExoticType type; public Void settype ({this.type = type;}} When it is created, we hope to specify an attribute in the form of a string, and one of the behind-the-scenes will convert this string into a real exotic type object. :

anameforexotictype and this PorpertyEditor looks like this: // Converts string representation to exotictype object

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. : Uppercase 3.14. Use the return value called by the method to set the attribute of the bean, some time, use the method of returning the value in the container to set a BEAN's attribute, or use other arbitrary classes (not necessarily the back value of the static method of the container) It is necessary to set up. In addition, it is also necessary to call a static or non-static approach to perform some initialization work. For these two purposes, there is a helper class called MethodInvokingFactoryBean. It is a FactoryBean that returns a call result for a static or non-static method. Below is an example of a bean definition, this bean defines the use of that assistant class call static factory method:

com.whatever.MyClassFactory.getInstance < / bean> The following example calls a static method and then calls an instance method to get a Java System's properties. Although it is a bit of a little, you can work:

java.lang.System getProperties getproperty java .version Note that this class is used to access the factory method, so MethodInvokingFactoryBean is operated by default in Singleton. The request of the Factory production object via the container will result in the call of the corresponding factory method, the return value of this method will be cached and returned to the request and later request. The Singleton attribute within this factory can be set to false, resulting in that target method that causes each object request. To set a static objective method by setting a string of a static method name to the targetMethod property, TargetClass is used to specify classes that define the static method. Similarly, you can also specify a target instance method. Set the target object through the targetobject property, the target object is set to the name of the method you want to call on the target object. The parameters of the method call can be specified by setting the Args property. 3.15. Creating an ApplicationContext in a web application is always created compared to BeanFactory, ApplicationContext can be declared by using a CONTEXTLOADER. Of course, you can also create it in any of the implementation of ApplicationContext. First, let's take a look at ContextLoader and its implementation. ContextLoader has two implementations: ContextLoaderListener and ContextLoaderServlet. Two have the same functionality, the difference is that Listener cannot be used in a container compatible with servlet2.2. Since the ServelT2.4 specification, Listener is required to initialize after the web application startup. Many compatible 2.3 containers have already achieved this feature.

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:

contextconfigLocation /web-inf/daocontext.xml /web-inf/applicationContext.xml org.springframework.web.context.ContextLoaderListener <-! OR USE THE CONTEXTLOADERSERVLET INSTEAD OF THE lISTENER context org.springframework.Web.context.contextloaderServlet 1 -> This listner needs Check the ContextConfigLocation parameter. If you don't exist, it uses /web-inf/applicationContext.xml by default. If it exists, it will separate the String with a pre-defined separator (comma, semicolon, and space) and use these values ​​as the location of Application Context. The ContextLoaderServlet replaces the ContextLoaderListener. This servlet will use the ContextConfigLocation parameter as Listener. 3.16. The bonded code and sin Singleton are mostly written in a style that relies on the injection (reverse control), which will be used by the BeanFactory container or ApplicationContext container, which will be in the container when created. It is worthy of its own dependencies, and they don't know the existence of the container at all. However, for a small amount of adhesive layer, it is sometimes necessary to bond it together with other code, and sometimes it is necessary to access beanFactory or ApplicationContext in a way in Singleton (or Singleton). For example, a third party's code may try directly to construct a new object (in the form of class.forname (), but there is no ability to get these objects from BeanFactory. If the 3-party code constructed is just a small STUB or Proxy, and use the Singleton mode to access beanfactrate / ApplicationContext to get real objects, so that reverse control is still role in most of the code (object generated by BeanFactory). So most of the code still don't know how the container's presence or how the container is accessed, and it is still decoupled with other code, and there is all of the benefits. EJB can use this STUB / Proxy program to an ordinary Java implementation object, which is generated by BeanFactory. While ideal BeanFactory does not need to be a Singleton, if each bean uses its own non-singleton's BeanFactory, it will be unrealistic due to memory usage or initialization time.

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

转载请注明原文地址:https://www.9cbs.com/read-101226.html

New Post(0)