Spring-annotation-based configuration) 4

Source: Internet
Author: User

1. Inject attributes using spring annotations
1.1. How did we inject attributes before using annotations?
Class implementation:
Java code

Public class usermanagerimpl implements usermanager {
Private userdao;
Public void setuserdao (userdao ){
This. userdao = userdao;
}
...
}

Configuration file:
Java code
<Bean id = "usermanagerimpl" class = "com. kedacom. Spring. annotation. Service. usermanagerimpl">

<Property name = "userdao" ref = "userdao"/>
</Bean>
<Bean id = "userdao" class = "com. kedacom. Spring. annotation. Persistence. userdaoimpl">

<Property name = "sessionfactory" ref = "mysessionfactory"/>
</Bean>

1.2. Introduce @ autowired annotation (not recommended. @ resource is recommended)
Class implementation (tagging member variables)
Java code
Public class usermanagerimpl implements usermanager {
@ Autowired
Private userdao;
...
}

Or (mark the method)
Java code
Public class usermanagerimpl implements usermanager {
Private userdao;
@ Autowired
Public void setuserdao (userdao ){
This. userdao = userdao;
}
...
}

Configuration File
Java code
<Bean id = "usermanagerimpl" class = "com. kedacom. Spring. annotation. Service. usermanagerimpl"/>

<Bean id = "userdao" class = "com. kedacom. Spring. annotation. Persistence. userdaoimpl">

<Property name = "sessionfactory" ref = "mysessionfactory"/>
</Bean>

@ Autowired can mark member variables, methods, and constructors to complete automatic assembly. In the preceding two different implementation methods, @ autowired has different annotation positions. They will automatically assemble the userdao attribute when spring initializes the bean usermanagerimpl. The difference is: in the first implementation, spring directly assigns a unique Bean Of The userdao type to the userdao member variable. In the second implementation, spring will call the setuserdao method to assemble the only Bean Of The userdao type into the userdao attribute.

1.3. Let @ autowired work
To enable @ autowired to work, add the following code to the configuration file:
Java code
<Bean class = "org. springframework. Beans. Factory. annotation. autowiredannotationbeanpostprocessor"/>

1.4. @ qualifier
@ Autowired is automatically assembled Based on the type. In the preceding example, if more than one bean of the userdao type exists in the spring context, the beancreationexception is thrown. If the bean of the userdao type does not exist in the spring context, beancreationexception will also be thrown. We can use @ qualifier with @ autowired to solve these problems.

1. There may be multiple userdao instances
Java code
@ Autowired
Public void setuserdao (@ qualifier ("userdao") userdao ){
This. userdao = userdao;
}

In this way, spring finds the bean whose ID is userdao for assembly.
2. The userdao instance may not exist.

Java code
@ Autowired (required = false)
Public void setuserdao (userdao ){
This. userdao = userdao;
}

1.5. @ Resource (JSR-250 standard annotation, it is recommended to replace spring proprietary @ autowired annotation)
Spring not only supports self-defined @ autowired annotations, but also supports several annotations defined by JSR-250 specifications, which are @ resource, @ postconstruct, and @ predestroy.

@ Resource is equivalent to @ autowired, but @ autowired is automatically injected by bytype, while @ resource is automatically injected by byname by default. @ Resource has two attributes, namely name and type. Spring resolves the name attribute of @ resource annotation to the bean name, And the type attribute to the bean type. Therefore, if the name attribute is used, the automatic injection policy of byname is used, and the automatic injection policy of bytype is used when the type attribute is used. If neither name nor type is specified, the byname automatic injection policy is used through reflection.

@ Resource Assembly Sequence

If both name and type are specified, a unique matching bean is found in the spring context for assembly. If no matching bean is found, an exception is thrown.
If the name is specified, the bean with the matching name (ID) is searched in the context for assembly. If no name is found, an exception is thrown.
If type is specified, an exception will be thrown if a unique bean of type matching is found in the context for assembly. If no or multiple beans are found, an exception will be thrown.
If neither name nor type is specified, the Assembly is automatically performed in byname mode (see figure 2). If no matching is found, the matching is performed in userdao mode, automatic Assembly is performed if matching is performed;

1.6. @ postconstruct (JSR-250)
Add the annotation @ postconstruct to the method. This method will be executed by the spring container after Bean initialization (Note: bean initialization includes instantiating bean, and assemble bean attributes (dependency injection )).

A typical application scenario is that when you need to inject an attribute defined in the parent class into the bean, and you cannot rewrite the attributes of the parent class or the setter method of the attribute, for example:
Java code
Public class userdaoimpl extends hibernatedaosupport implements userdao {
Private sessionfactory mysessionfacotry;
@ Resource
Public void setmysessionfacotry (sessionfactory sessionfacotry ){
This. mysessionfacotry = sessionfacotry;
}
@ Postconstruct
Public void injectsessionfactory (){
Super. setsessionfactory (mysessionfacotry );
}
...
}

Here, @ postconstruct is used to inject the sessionfactory private attribute defined in the userdaoimpl parent class into our own sessionfactory (the setsessionfactory method of the parent class is final and cannot be rewritten ), then we can call super. getsessionfactory () to access this attribute.

1.7. @ predestroy (JSR-250)
Add the annotation @ predestroy to the method. This method will be executed by the spring container after Bean initialization. We do not need to use it for the moment, so we will not describe it here. Its usage is the same as @ postconstruct.

1.8. Use <context: annotation-config/> to simplify the configuration
Spring2.1 adds a schema namespace for the new context, which provides convenient configuration for the annotation driver, attribute file introduction, and loading period weaving functions. We know that the annotation itself does not do anything, and it only provides metadata information. To make the metadata really take effect, the processor responsible for processing the metadata must work.

Autowiredannotationbeanpostprocessor and commonannotationbeanpostprocessor are the processors that process the annotation metadata. However, defining these beans in the spring configuration file is clumsy. Spring provides us with a convenient way to register these beanpostprocessor, Which is <context: annotation-config/>:

Java code
<Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context"

Xsi: schemalocation = "http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-2.5.xsd>
<Context: annotation-config/>
</Beans>

<Context: annotationconfig/> the autowiredannotationbeanpostprocessor, commonannotationbeanpostprocessor, persistenceannotationbeanpostprocessor, and requiredannotationbeanpostprocessor will be implicitly registered with the spring container.

2. Use spring annotations to define beans
The above section describes how to implement automatic injection in bean through @ autowired or @ resource. Next we will introduce how to annotate bean to completely remove bean-defined configuration from the xml configuration file.

2.1. @ component (not recommended), @ repository, @ service, @ Controller
You only need to add a @ component annotation to the corresponding class to define the class as a bean:
Java code
@ Component
Public class userdaoimpl extends hibernatedaosupport implements userdao {
...
}

For the bean defined using the @ component annotation, the default name (ID) is an unqualified class name starting with lowercase. For example, the bean name defined here is userdaoimpl. You can also specify the bean Name:

@ Component ("userdao ")
@ Component is a common form of all spring management components. Spring also provides more refined annotation forms: @ repository, @ service, and @ controller, which correspond to the storage layer beans respectively, service layer bean and presentation layer bean. In the current version (2.5), these annotations have the same semantics as @ component and are completely universal. In Versions later than spring, more semantics may be added to them. Therefore, we recommend @ repository, @ service, and @ controller to replace @ component.

2.2. Use <context: component-Scan/> to make bean definition annotations work.
Java code
<Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context"

Xsi: schemalocation = "http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-2.5.xsd>
<Context: component-scan base-package = "com. kedacom. ksoa"/>
</Beans>

Here, all the configuration content of bean defined through the <bean> element has been removed. You only need to add one <context: the component-Scan/> Configuration solves all the problems-the spring xml configuration file is simplified to the extreme (of course, the configuration metadata is still needed, but it only exists in the form of annotations ). <Context: component-Scan/> specifies the class package to be scanned. All classes in the class package and Its Recursive Sub-package are processed.

<Context: component-Scan/> also allows you to define filters to include or exclude certain classes in the base package. Spring supports the following four types of filtering methods:

Examples of filter type expressions
Annotation org. example. someannotation filters out all classes using the someannotation annotation.
The class name specifies org. example. someclass to filter the specified class.
Regular Expression com ". kedacom". Spring ". annotation". Web "... * filter some classes using regular expressions
Aspectj expression org. Example... * Service + filter some classes using aspectj expressions

Taking a regular expression as an example, I will list an application example:
Java code
<Context: component-scan base-package = "com. casheen. Spring. annotation">
<Context: exclude-filter type = "RegEx" expression = "com". casheen ". Spring". annotation ". Web"... * "/>

</Context: component-scan>

It is worth noting that the <context: component-Scan/> configuration item not only enables scanning of class packages to implement the annotation-driven bean definition function, the annotation driver automatic injection function is also enabled (that is, autowiredannotationbeanpostprocessor and commonannotationbeanpostprocessor are implicitly registered internally). Therefore, when <context: component-Scan/> is used, you can remove <context: annotation-config/>.

2.3. Use @ scope to define the bean Scope
When using XML to define beans, we may also need to define the scope of a bean through the scope attribute of bean. We can also do this through the @ scope annotation:
Java code
@ Scope ("session ")
@ Component ()
Public class usersessionbean implements serializable {
...
}

3. Reference

 
Http://kingtai168.javaeye.com/blog/244002
Http://www.javaeye.com/topic/244153

Http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config

Http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-classpath-scanning

Http://www.bianceng.cn/Programming/Java/201103/24807_4.htm

Http://www.bianceng.cn/Programming/Java/201103/24807_4.htm

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.