Spring3 development practice Chapter 2: IoC/DI Development (2)

Source: Internet
Author: User


You can use the <list/>, <set/>, <map/>, and <props/> elements to define and Set the values of List, set, Map, and Properties corresponding to the Java Collection type, example:

Java code:
[Java]
<Bean id = "moreComplexObject" class = "example. ComplexObject">
<Property name = "adminEmails">
<Props>
<Prop key = "administrator"> admin@somecompany.org </prop>
<Prop key = "support"> support@somecompany.org </prop>
</Props>
</Property>
<Property name = "someList">
<List>
<Value> a list element followed by a reference </value>
<Ref bean = "myDataSource"/>
</List>
</Property>
<Property name = "someMap">
<Map>
<Entry>
<Key> <value> yup an entry </value> </key>
<Value> just some string </value>
</Entry>
<Entry>
<Key> <value> yup a ref </value> </key>
<Ref bean = "myDataSource"/>
</Entry>
</Map>
</Property>
<Property name = "someSet">
<Set>
<Value> just some string </value>
<Ref bean = "myDataSource"/>
</Set>
</Property>
</Bean>
You can define the <list/>, <map/>, <set/>, or <props/> elements of parent-style and child-style, the values of a child set are inherited and overwritten from its parent set. That is, the merged values of elements in the child set are the final results of the child set, and the element values in the child set overwrite the values in the parent set.

Java code:
[Java]
<Beans>
<Bean id = "parent" abstract = "true" class = "example. ComplexObject">
<Property name = "adminEmails">
<Props>
<Prop key = "administrator"> administrator@somecompany.com </prop>
<Prop key = "support"> support@somecompany.com </prop>
</Props>
</Property>
</Bean>
<Bean id = "child" parent = "parent" class = "example. Child">
<Property name = "adminEmails">
<Props merge = "true">
<Prop key = "sales"> sales@somecompany.com </prop>
<Prop key = "support"> support@somecompany.co.uk </prop>
</Props>
</Property>
</Bean>
<Beans>
In the preceding example, the <props/> element of the adminEmails attribute of childbean uses the merge = true attribute. When the child bean is parsed and instantiated by the container, its adminEmails will be merged with the adminEmails attribute of the parent set.
Note that the Properties set of the Child bean inherits all attribute elements from the parent <props/>. The support Value of the Child bean overwrites the corresponding value of the parent set.
Different set types cannot be merged (for example, map and list cannot be merged). Otherwise, an Exception is thrown. The merge attribute must be defined in the inherited child bean, and the merge attribute specified on the collection attribute of the parent bean will be ignored.
In JDK 5 or a later version, Spring supports a set of strong types.
<Null/> it is used to process null values. Spring treats null parameters of the attribute as null strings.
1: The following xml snippets set the email attribute to a null string.
<Bean class = "ExampleBean">
<Property name = "email"> <value> </property>
</Bean>
This is equivalent to Java code: exampleBean. setEmail ("").
2: The null value can be expressed using the <null> element. For example:
<Bean class = "ExampleBean">
<Property name = "email"> <null/> </property>
</Bean>
The above configuration is equivalent to the Java code: exampleBean. setEmail (null ).
Spring provides a simplified format to replace <value/> and <ref/> elements with common value values or bean references. As follows:

Java code:
[Java]
<Property name = "myProperty">
<Value> hello </value>
</Property>
<Property name = "myProperty">
<Ref bean = "myBean">
</Property>
<Entry>
<Key>
<Ref bean = "myKeyBean"/>
</Key>
<Ref bean = "myValueBean"/>
</Entry>
Completely equivalent
<Property name = "myProperty" value = "hello"/>
<Property name = "myProperty" ref = "myBean"/>
<Entry key-ref = "myKeyBean" value-ref = "myValueBean"/>
 
Emphasize one point
Only <ref bean = "xxx"> elements are abbreviated. <ref local = "xxx"> is not abbreviated. That is to say, the ref in <property name = "myProperty" ref = "myBean"/> is equivalent to the <ref bean = ""> format.
Attribute combination name
When setting the bean combination attribute, except for the last attribute, the combination or nested attribute name is completely legal as long as the other attribute values are not null. For example, the following bean definition:

Java code:
[Java]
<Bean id = "foo" class = "foo. Bar">
<Property name = "fred. bob. sammy" value = "123"/>
</Bean>
Foo

Bean has a fred attribute, which has a bob attribute, while the bob attribute has a sammy attribute. Finally, set the sammy attribute to 123. To make this definition work, the fred attribute of foo and the bob attribute of fred must be non-null after the bean is constructed. Otherwise, an NullPointerException exception will be thrown.
Depends-on is used to explicitly force one or more beans to be initialized before the current bean initialization.
Example:

Java code:
[Java]
<Bean id = "beanOne" class = "ExampleBean" depends-on = "manager"/>
<Bean id = "manager" class = "ManagerBean"/>

To express dependencies on multiple beans, you can separate multiple bean names by commas (,), spaces (,), and semicolons (;) in 'depends-on. The following example uses 'depends-on' to express dependencies on multiple beans.
 

Java code:
[Java]
<Bean id = "beanOne" class = "ExampleBean" depends-on = "manager, accountDao">
<Property name = "manager" ref = "manager"/>
</Bean>
<Bean id = "manager" class = "ManagerBean"/>
<Bean id = "accountDao" class = "x. y. jdbc. JdbcAccountDao"/>
Delayed bean Initialization
1: The default behavior implemented by ApplicationContext is to instantiate all singleton beans in advance at startup, which may increase resource consumption but speed up program running.
 
2: bean can be set to delayed instantiation. In the XML configuration file, delayed Initialization is controlled by the lazy-init attribute in the <bean/> element. For example:
<Bean id = "lazy" class = "com. foo. ExpensiveToCreateBean" lazy-init = "true">
</Bean>
 
3: it is also possible to control delayed initialization by using the 'default-lazy-init 'attribute on the <beans/> element in the container hierarchy. The configuration is as follows:
<Beans default-lazy-init = "true">
</Beans>

 
Advantages and disadvantages of automatic assembly
1: advantages:
(1) automatic assembly can significantly reduce the number of configurations.
(2) automatic assembly can synchronize configuration and java code updates. For example, if you need to add a dependency to a java class, the dependency will be automatically implemented without modifying the configuration.
2. Disadvantages:
(1) Although automatic assembly is more amazing than explicit assembly, as mentioned above, Spring will try its best to avoid speculation when the Assembly is unclear, unexpected results may occur due to unclear assembly, and the association between objects managed by Spring cannot be clearly documented.
(2) For tools that generate documents based on Spring configuration files, automatic assembly will make these tools unable to generate dependency information.
(3) When automatic assembly is performed based on the type, multiple bean definitions in the container may match the setter method of automatic assembly with the type of the constructor parameter. Although this problem does not exist for arrays, sets, and maps, there will be ambiguity for Single-value dependencies. If the bean definition is not unique, an exception is thrown during assembly.
Exclude beans from automatic assembly
1: The autowire-candidate attribute of the <bean/> element can be set to false, so that the container does not consider this bean when searching for an automatically assembled object.
2: Another approach is to use pattern matching for bean names to restrict automatic assembly. The method is to set it in the 'default-autowire-candidates' attribute of the <beans/> element.
For example, you can set automatic assembly to "* Repository" if the bean name ends with 'reposition'. Multiple matching modes can be separated by commas. Note: If the 'autowire-candidate' attribute in the bean definition is explicitly set to 'true' or 'false ', the container uses the setting of this attribute in priority during automatic assembly, and pattern matching does not work.

Singleton
A bean definition in each Spring IoC container corresponds to an object instance. when reading the configuration file and creating an IoC container, the Bean instance of singleton is initialized according to the configuration.
Prototype
A bean defines multiple object instances.
Request
In an HTTP request, a bean corresponds to an instance, that is, each HTTP request will have its own bean instance, which is created based on a bean definition. This scope is only valid in the case of web-based Spring ApplicationContext.







Session
In an HTTP Session, a bean defines an instance. This scope is only valid in the case of web-based Spring ApplicationContext.
Global session
In a global HTTP Session, a bean defines an instance. In typical cases, it is valid only when the portlet context is used. This scope is only valid in the case of web-based Spring ApplicationContext.

 
 
Requests, sessions, and global sessions are only used in web-based applications.
Initialize the web configuration. For web containers of Servlet 2.4 and later, configure the following:

Java code:
[Java]
<Web-app>
<Listener>
<Listener-class> org. springframework. web. context. request. RequestContextListener </listener-class>
</Listener>
</Web-app>
Request scope description
Equivalent to Http Request
Session scope description
For an HTTP Session, the Spring container creates a brand new bean instance according to bean definitions, and the bean is only valid in the current HTTP Session. Similar to the request scope, you can change the internal status of the created instance based on your needs, while the instances created in other HTTP sessions, the status changes specific to an HTTP Session will not be seen. When an HTTP Session is discarded, the bean in the HTTP Session scope will also be discarded.
Global session
Equivalent to standard HTTP Session
Problem: for example, when calling A method of A singleton bean A, you need to reference another bean B of A non-singleton (prototype) type. For bean A, the container will only be created once, in this way, the container cannot provide A new bean B instance for bean A every time when necessary.
Solution: Lookup method injection, for example:

Java code:
[Java]
Java class
Public abstract class HelloImpl implements HelloApi {
Private T2 t2;
Public String helloSpring3 (int ){
GetT2 (). t1 ();
System. out. println ("hello Spring3 =" + );
Return "OK, a =" +;
}
Public abstract T2 getT2 ();
}
Public class T2 {
Public void t1 (){
System. out. println ("now in t1 ");
}
}
Configuration file:

Java code:
[Java]
<Bean id = "helloBean" class = "cn. S. Spring3.hello. HelloImpl">
<Lookup-method name = "getT2" bean = "t2"/>
</Bean>
<Bean id = "t2" class = "cn. S. Spring3.hello. T2"> </bean>

The internal mechanism of Lookup method injection is that Spring uses the CGLIB library to generate binary code at runtime. By dynamically creating child classes of the Lookup method bean, The Lookup method can be rewritten.
Initialization callback
There are two methods:
1: implement the org. springframework. beans. factory. InitializingBean interface. This method is not recommended because it is coupled with Spring. You can use the declarative method as follows:
2: specify a common Initialization method in the Bean definition. That is, you can specify the init-method attribute in the XML configuration file. The configuration is as follows:
<Bean id = "initBean" class = "examples. ExampleBean" init-method = "init"/>
Destructor callback
There are also two methods:
1: implement the org. springframework. beans. factory. DisposableBean interface. This method is not recommended because it is coupled with Spring. You can use the declarative method as follows:
<Bean id = "initBean" class = "ex. ExampleBean" destroy-method = "cleanup"/>
Default initialization and destructor
Configure it on beans so that no Bean is configured as follows:
<Beans default-init-method = "init">
The core of the context package is the ApplicationContext interface. It is derived from the BeanFactory interface. In addition to providing all BeanFactory functions, it also provides the following features:
1: MessageSource, providing international Message Access
2: resource access, such as URLs and files
3: Event propagation implements the bean of the ApplicationListener interface.
4: Load multiple (inherited) contexts so that each context is focused on a specific level, such as the web layer of the application.
Use MessageSource for internationalization
1: add

Java code:
[Java]
<Bean id = "messageSource" class = "org. springframework. context. support. ResourceBundleMessageSource">
<Property name = "basenames">
<List>
<Value> format </value>
<Value> exceptions </value>
</List>
</Property>
</Bean>
2: Note: The above configuration indicates that there are two standard properties files under classpath. The file format is a standard properties format. Spring uses ResourceBundle to parse messages in JDK in a standard way to process any request for parsing messages.
3: Test code:
String msg = context. getMessage ("testmsg", null, "Default", Locale. CHINA );
The second parameter of the preceding getmessage method is used to pass values into the message from the program, as follows:

Java code:
[Java]
Message file: testmsg = this is a test, {0}, {1}
Java class: String msg = context. getMessage ("testmsg ",
Ew Object [] {"M1", "M2"}, "Default", Locale. CHINA );
System. out. println ("msg =" + msg );
The fourth parameter of the preceding getmessage method is used to specify the Locale
For i18n, different MessageResource implementations in Spring are the same as the locale parsing rules in the JDK standard ResourceBundle. For example, in the messageSource bean defined in the above example, if you want to parse the message of the British (en-GB) locale, you need to create a resource file for format_en_GB.properties; for example, msg_zh_CN.properties in China. Locale resolution is usually specified by the application according to the runtime environment.
You can also inject MessageSource into Bean as a resource. The Java class example is as follows:

Java code:
[Java]
Public class HelloImpl implements HelloApi {
Private MessageSource MS = null;
Public void setMs (MessageSource MS ){
This. ms = ms;
}
Public String helloSpring3 (int ){
String msg = this. ms. getMessage ("testmsg", null, "Default", Locale. CHINA );
System. out. println ("hello Spring3 =" + msg );
Return "OK, a =" +;
}
}
The configuration file is as follows:

Java code:
[Java]
<Bean id = "helloBean" class = "cn. S. Spring3.hello. HelloImpl">
<Property name = "ms" ref = "messageSource"> </property>
</Bean>
Event Propagation
Event Processing in ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. If you deploy a bean that implements the ApplicationListener interface in the context, the bean will be notified whenever an ApplicationEvent is published to ApplicationContext.
Spring provides three standard events:
ContextRefreshedEvent
Events sent when ApplicationContext is initialized or refreshed. Initialization means that all beans are loaded, singleton is pre-instantiated, and ApplicationContext is ready for use.
ContextClosedEvent
Event sent when the context is ended using the close () method of ApplicationContext. The end means that singleton bean is destroyed.
RequestHandledEvent
A web-related event tells all beans that an HTTP request has been responded (that is, this event will be sent after a request ends ). Note: Only web applications that use DispatcherServlet in Spring can use
 
Example: Java class:

Java code:
[Java]
Public class T2 implements ApplicationListener {
@ Override
Public void onApplicationEvent (ApplicationEvent arg0 ){
System. out. println ("event occurred =" + arg0 );
}
}
 
Configuration File
<Bean id = "t2" class = "cn. S. Spring3.hello. T2"> </bean>
Resource interface:
Spring's Resource interface aims to provide more abstract capabilities for accessing underlying resources, typically accessing File resources. The basic definition is as follows:

Java code:
[Java]
Public interface Resource extends InputStreamSource {
Boolean exists ();
Boolean isOpen ();
URL getURL () throws IOException;
File getFile () throws IOException;
Resource createRelative (String relativePath) throws IOException;
String getFilename ();
String getDescription ();
}
Public interface InputStreamSource {
InputStream getInputStream () throws IOException;
}
You can use ApplicationContext to directly access resources, for example:

Java code:
[Java]
InputStream in = context. getResource ("msg_en_GB.properties"). getInputStream ();
Byte bs [] = new byte [100];
In. read (bs );
System. out. println ("file content =" + new String (bs ));
You can also inject resources into the Bean, for example:
Add the following to the Java class:

Java code:
[Java]
Private Resource rs = null;
Public void setRs (Resource rs ){
This. rs = rs;
}
In the configuration file:

Java code:
[Java]
<Bean id = "helloBean" class = "cn. S. Spring3.hello. HelloImpl">
<Property name = "rs" value = "msg_en_GB.properties"> </property>
</Bean>
ApplicationContext can be created as declared. The configuration in web. xml is as follows:

Java code:
[Java] www.2cto.com
<Context-param>
<Param-name> contextConfigLocation </param-name>
<Param-value>/WEB-INF/daoContext. xml/WEB-INF/applicationContext. xml </param-value>
</Context-param>
<Listener>
<Listener-class> org. springframework. web. context. ContextLoaderListener </listener-class>
</Listener>
Author: jinnianshilongnian

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.