Explanation of the use of annotations in the spring framework of Java

Source: Internet
Author: User
Tags deprecated

Reprint: http://www.jb51.net/article/75460.htm

1. Using spring annotations to inject attributes

1.1. How do we inject attributes before using annotations?
Implementation of the class:

Class Usermanagerimpl implements Usermanager {   private Userdao Userdao;   public void Setuserdao (Userdao userdao) {     This.userdao = Userdao;   }   ... }

Configuration file:

<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. Introduction of @autowired annotations (deprecated, recommended for use with @resource)
Implementation of the class (labeling member variables)

public class Usermanagerimpl implements Usermanager {   @Autowired   private Userdao Userdao;   ... }

or (annotate the method)

Usermanagerimpl implements Usermanager {   private Userdao Userdao;   @Autowired public   void Setuserdao (Userdao userdao) {     This.userdao = Userdao;   }   ... }

Configuration file

<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 label member variables, methods, and constructors to accomplish the task of automating Assembly. In the two different implementations, the @Autowired label positions are different, they will automatically assemble the Userdao attribute when spring initializes the Usermanagerimpl bean, the difference being: the first implementation, Spring directly assigns the only bean of the Userdao type to the member variable of Userdao, and in the second implementation, spring calls the Setuserdao method to assemble the only bean of the Userdao type into the Userdao property.

1.3. Let @autowired work
To enable @autowired to work, you also need to include the following code in the configuration file

class= "Org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

1.4. @Qualifier
@Autowired are automatically assembled according to the type. In the above example, if there is more than one Userdao type of bean in the spring context, the beancreationexception exception is thrown, and if the Userdao type of bean does not exist in the spring context, Beancreationexception exceptions are also thrown. We can use @qualifier with @autowired to solve these problems.
1. Multiple Userdao instances may exist

@Autowired public void Setuserdao (@Qualifier ("Userdao") Userdao Userdao) {   This.userdao = Userdao;}

In this way, spring will find the bean with ID userdao to assemble.
2. Userdao instances may not exist

@Autowired (required = false) public void Setuserdao (Userdao Userdao) {   

1.5. @Resource (JSR-250 standard note, recommended for use in place of Spring proprietary @autowired annotations)
Spring not only supports its own defined @autowired annotations, it also supports several annotations defined by the JSR-250 specification, namely @resource, @PostConstruct, and @predestroy.
The function of the @Resource is equivalent to @autowired, but @autowired is automatically injected by Bytype, and @resource is automatically injected by ByName by default. It is important to @Resource that there are two properties, namely name and type,spring, which resolves the name property of the @resource annotation to the bean, while the type attribute resolves to the bean. So if you use the Name property, you use the ByName Auto-injection policy, and the Type property uses the Bytype auto-injection policy. If neither name nor the type attribute is specified, the ByName auto-injection policy is used through the reflection mechanism.
@Resource Assembly Order

If name and type are specified at the same time, a uniquely matched bean is found from the spring context to assemble, and an exception is thrown if it is not found
If name is specified, a bean matching the name (ID) from the context is assembled, and an exception is thrown if it is not found
If type is specified, the unique bean that matches the type found in the context is assembled, cannot be found, or multiple occurrences are thrown, throwing an exception
If neither name is specified and type is not specified, the assembly is automatically byname (see 2), and if there is no match, the fallback is matched to an original type (Userdao) and automatically assembled if matched;
1.6. @PostConstruct (JSR-250)
By adding annotation @postconstruct to the method, this method is executed by the spring container after the bean is initialized (note: Bean initialization includes, instantiates the bean, and assembles the Bean's attributes (Dependency injection)).
A typical application scenario is when you need to inject a property defined in a parent class into a bean, and you cannot replicate the setter method of a property or property of the parent class, such as:

public class Userdaoimpl extends Hibernatedaosupport implements Userdao {   private sessionfactory mysessionfacotry;< c1/> @Resource public   void Setmysessionfacotry (Sessionfactory sessionfacotry) {     this.mysessionfacotry = sessionfacotry;   }   @PostConstruct public   void Injectsessionfactory () {     super.setsessionfactory (mysessionfacotry);   }   ... }

Here is a sessionfactory private attribute defined in Userdaoimpl's parent class by @postconstruct, Injected with our own defined sessionfactory (the parent class's Setsessionfactory method is final, non-reproducible), then we can access the property by calling Super.getsessionfactory ().


1.7. @PreDestroy (JSR-250)
By adding annotation @predestroy to the method, the method is executed by the spring container after the bean is initialized. Since we don't have a scene to use it at the moment, we're not going to show it here. Its usage is the same as @postconstruct.

1.8. Simplify configuration with <context:annotation-config/>
Spring2.1 adds a new context schema namespace that provides a convenient configuration for annotation drivers, attribute file ingestion, and load-time weaving. We know that the annotation itself will not do anything, it only provides meta-data information. For the metadata information to really work, you must let the processor responsible for processing the metadata work.
Autowiredannotationbeanpostprocessor and Commonannotationbeanpostprocessor are processors that process these annotation metadata. But defining these beans directly in the spring configuration file looks awkward. Spring provides us with a convenient way to register these beanpostprocessor, which is <context:annotation-config/>:

<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/> will implicitly register autowiredannotationbeanpostprocessor with the spring container, Commonannotationbeanpostprocessor, Persistenceannotationbeanpostprocessor and Requiredannotationbeanpostprocessor the 4 beanpostprocessor.

2. Using spring Annotations to complete the bean definition
We have introduced the ability to automatically inject in beans via @autowired or @resource, and we will show you how to annotate the bean to completely remove the bean-defined configuration from the XML configuration file.

2.1. @Component (deprecated), @Repository, @Service, @Controller
Just add a @component annotation to the corresponding class and define the class as a bean:

@Component public class Userdaoimpl extends Hibernatedaosupport implements Userdao {   ...}

Using the bean defined by the @component annotation, the default name (ID) is the unqualified class name beginning with lowercase. The bean name defined here is Userdaoimpl. You can also specify the name of the bean:
@Component ("Userdao")
@Component is a common form of all spring-managed components, and spring also provides a more granular form of annotations: @Repository, @Service, @Controller, which correspond to storage-tier beans, business-layer beans, and presentation layer beans. In the current version (2.5), these annotations are the same as the semantics of @component, and are completely generic, and may add more semantics to them in later versions of spring. Therefore, we recommend the use of @repository, @Service, @Controller to replace @component.

2.2. Use <context:component-scan/> To make bean definition annotations work

<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 contents of the bean defined through the <bean> element have been removed, and only one line of <context:component-scan/> configuration will be added to solve all the problems--spring The XML configuration file is extremely simplified (of course, configuration metadata is still needed, only in the form of annotations). The Base-package property of the <context:component-scan/> Specifies the class package that needs to be scanned, and all classes in the class package and its recursive child packages are processed.
<context:component-scan/> also allows defining filters to include or exclude certain classes under the base package. Spring supports the following 4 types of filtering methods:

Filter Type Expression Example description
Annotation Org.example.SomeAnnotation filter out all classes that use someannotation annotations
Class name Specifies Org.example.SomeClass filter the specified class
Regular expression com\.kedacom\.spring\.annotation\.web\: * Filter Some classes with regular expressions
AspectJ expression org.example: *service+ filtering some classes by ASPECTJ expressions

In the case of regular expressions, I will cite an example of an application:

<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 important to note that the <context:component-scan/> configuration item not only enables the ability to scan the class package to implement the annotation-driven bean definition. Note-driven auto-injection is also enabled (i.e., autowiredannotationbeanpostprocessor and commonannotationbeanpostprocessor are also implicitly registered internally), so when using < After Context:component-scan/>, you can remove the <context:annotation-config/>.

2.3. Use @scope to define the scope of the bean
When using XML to define beans, we may also need to define the scope of a bean through the bean's scope property, and we can do this by @scope annotations as well:

@Scope ("session") @Component () public class Usersessionbean implements Serializable {   ...}

3. Define a relationship between three beans before using annotation.

Package Com.baobaotao;public class Office {  private String Officeno = "001";   Omit Get/setter   @Override public  String toString () {    return "Officeno:" + Officeno;  }} Ackage Com.baobaotao; public class Car {  private String brand;  private double price;   Omit Get/setter   @Override public  String toString () {    return ' Brand: ' + brand + ', ' + ' Price: ' + price;
   }}package Com.baobaotao; public class Boss {  private car car;  Private Office Office;   Omit Get/setter   @Override public  String toString () {    return "car:" + car + "\ n" + "office:" + office;
   
    }}
   

The configuration file is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"  Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"  xsi:schemalocation= "http://www.springframework.org/ Schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd ">  <bean id=" Boss " class= "Com.baobaotao.Boss" >    <property name= "car" ref= "car"/>    <property name= "office" ref= " Office "/>  </bean>  <bean id=" office "class=" Com.baobaotao.Office ">    <property name=" Officeno "value=" 002 "/>  </bean>  <bean id=" car "class=" Com.baobaotao.Car "scope=" Singleton " >    <property name= "brand" value= "Red flag CA72"/>    <property name= "Price" value= "$"/>  < /bean></beans>

The test files are as follows:

Import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Annoioctest {public   static void Main (string[] args) {    string[] locations = {"Beans.xml"};    ApplicationContext CTX =       new Classpathxmlapplicationcontext (locations);    Boss Boss = (boss) Ctx.getbean ("Boss");    SYSTEM.OUT.PRINTLN (Boss);}  }


4. Next we can use autowired to annotate , he can the member variables, methods and constructors to standard, complete the work of automatic assembly.

Autoware to annotate the use of member variables

Package Com.baobaotao;import org.springframework.beans.factory.annotation.Autowired; public class Boss {   @Autowired  private car car;   @Autowired  Private Office office;   ...}

The corresponding configuration file is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"  Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"  xsi:schemalocation= "http://www.springframework.org/ Schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd ">   <!--the The beanpostprocessor will automatically function and automatically inject the Bean labeled @Autowired--  <bean class= " Org.springframework.beans.factory.annotation.    Autowiredannotationbeanpostprocessor "/>   <!--Remove the attribute injection configuration information for the boss Bean--  <bean id=" Boss "class=" Com.baobaotao.Boss "/>   <bean id=" office "class=" Com.baobaotao.Office ">    <property name=" Officeno "value=" 001 "/>  </bean>  <bean id=" car "class=" Com.baobaotao.Car "scope=" Singleton " >    <property name= "brand" value= "Red flag CA72"/>    <property name= "Price" value= "$"/>  < /bean></beans>

Autoware can also be used on setter methods and constructors

Package Com.baobaotao; public class Boss {  private car car;  Private Office Office;    @Autowired public  void Setcar (car car) {    This.car = car;  }   @Autowired public  void Setoffice (Office office) {    this.office = office;  }  ...} Package Com.baobaotao; public class Boss {  private car car;  Private Office Office;   @Autowired public  Boss (car car, office Office) {    this.car = car;    this.office = Office;  }   ...}

When the number of candidate beans is 0 o'clock, we can use @autowired (required = false) to prevent spring from finding the bean times error.

When there are multiple candidate beans, we can specify the name of the injected bean through the @qualifier comment.

When @Autowired and @Qualifier are used together, the automatic injection strategy is transformed from Bytype to ByName. @Autowired can comment on member variables, methods, and constructors, while @Qualifier label objects are member variables, method entry parameters, constructor arguments. Because of the different annotation objects, Spring does not unify the @Autowired and @Qualifier into a single annotation class.

[email protected] is reflected according to the name , he has two parameters, name and type, using the name is to follow the byname to map, using the type is to follow the bytype to map.

Package Com.baobaotao; Import Javax.annotation.Resource; public class Boss {  //automatically injects Bean of type car  @Resource  private car car;   Automatically inject bean name called Office Bean  @Resource (name = "Office")  Private office Office;} @postconstructor and predestory are used to annotate the class after initialization and before the method is destroyed. Package Com.baobaotao; Import Javax.annotation.resource;import Javax.annotation.postconstruct;import Javax.annotation.PreDestroy; public class Boss {  @Resource  private car car;   @Resource (name = "Office")  Private office office;   @PostConstruct public  void PostConstruct1 () {    System.out.println ("PostConstruct1");  }   @PreDestroy public  void PreDestroy1 () {    System.out.println ("preDestroy1");   }  ...}

[email protected] You can define the bean directlyso that you do not need to configure the bean in the XML configuration file.

Package Com.baobaotao; Import org.springframework.stereotype.Component; @Componentpublic class Car {  ...} Package Com.baobaotao; Import org.springframework.stereotype.Component; @Componentpublic class Office {  private String Officeno = "001";  ...} Package Com.baobaotao; Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.required;import Org.springframework.beans.factory.annotation.qualifier;import org.springframework.stereotype.Component; @Component ("Boss") public class Boss {  @Autowired  private car car;   @Autowired  Private Office office;  ...}

The @Component has an optional entry parameter that specifies the name of the bean, and in the boss we define the bean name as "Boss". In general, beans are singleton and need to be injected into the bean only by Bytype policy, so it is not necessary to specify the name of the bean.

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"  Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"  xmlns: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.baobaotao"/></beans>

[email protected] can be used to specify its target

Package Com.baobaotao;import Org.springframework.context.annotation.Scope, ... @Scope ("prototype") @Component ("Boss") public class Boss {


In addition to providing @Component annotations in Spring 2.5, several annotations with special semantics are defined, namely, @Repository, @Service, and @Controller. In the current Spring version, these 3 comments and @Component are equivalent, but from the name of the annotation class it is easy to see that the 3 annotations correspond to the persistence layer, the business layer, and the control layer (the WEB layer), respectively. Although there is nothing new about these 3 annotations and @Component, Spring will add special features to them in future releases. Therefore, if a WEB application uses a classic three-tier hierarchy, it is best to annotate the classes in the hierarchy by using @Repository, @Service, and @Controller, respectively, in the persistence layer, the business layer, and the control layer @Component Comment on those classes that are more neutral.

Explanation of the use of annotations in the spring framework of Java

Related Article

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.