Spring Annotation Daquan

【转载】https://www.cnblogs.com/zxf330301/articles/6559210.html

The role of spring @component

1. @controller controller (injection service)
2. @service service (inject dao)
3. @repository dao (implementing dao access)
4. @component (instantiate ordinary pojo into the spring container, which is equivalent to <bean id="" class=""/> in the configuration file)
 
 
 
 
  @Component, @Service, @Controller, @Repository annotated classes, and incorporate these classes into the spring container for management. 
Write this below to introduce the scanning component of component 
<context:component-scan base-package=”com.mmnc”>    

where base-package is the package to be scanned (including all sub-packages) 
       1. @Service is used to mark business layer components 
       2. @Controller is used to label control layer components (such as actions in struts) 
       3. @Repository is used to label data access components, namely DAO components. 
       4. @Component refers to components in general. When components are not well classified, we You can use this annotation for annotation.    
           @Service public class UserServiceImpl implements UserService { } 
           @Repository public class UserDaoImpl implements UserDao { } The default name of getBean is the class name (initial lowercase), if you want to customize it, you can specify it like @Service("***"), This bean is a singleton by default. If you want to change it, you can use @Service("beanName") 
           @Scope("prototype") to change. The initialization method and destruction method can be specified in the following way (the method name is arbitrary): @PostConstruct public void init() { } 

Difference between @Autowired and @Resource

1. Both @Autowired and @Resource can be used to assemble beans. Both can be written on fields, or on setter methods. 
2. @Autowired is assembled by type by default (this annotation belongs to spring ). By default, the dependent object must exist. If you want to allow null values, you can set its required property to false, such as: @Autowired(required= false) , if we want to use name assembly, we can use it in conjunction with the @Qualifier annotation, as follows: 

Java code   Favorite code
  1. @Autowired() @Qualifier("baseDao")     
  2. private BaseDao baseDao;    

 3. @Resource (this annotation belongs to J2EE), the assembly is performed according to the name by default. The name can be specified by the name attribute. 
If the name attribute is not specified, when the annotation is written on the field, the field name is used by default to search by name. If the annotation is written on the setter method, the attribute name is used for assembly by default. Assemble by type when no bean matching the name is found. But it should be noted that if the name attribute is specified, it will only be assembled according to the name.

Java code   Favorite code
  1. @Resource(name="baseDao")     
  2. private BaseDao baseDao;    

In Java code, you can use @Autowire or @Resource annotations for assembly. The difference between these two annotations is:
@Autowire is assembled by type by default. By default, it requires that the dependent object must exist. If it is allowed to be null, you can set its required attribute If it is false, if we want to use assembly by name, it can be used in conjunction with the @Qualifier annotation;


@Resource is assembled by name by default. When no bean matching the name is found, it will be assembled by type. It can be specified by the name attribute. If the name attribute is not specified, when the annotation is marked on the field, the name of the field is used as the bean name by default. Find the dependent object, when the annotation is marked on the property's setter method, that is, by default, the property name is used as the bean name to find the dependent object.

 
 
Various annotation methods

1. @Autowired annotation (not recommended, @Resource is recommended)

@Autowired can annotate member variables, methods and constructors to complete the work of autowiring. The annotation positions of @Autowired are different, and they will automatically wire this property when Spring initializes the bean. For @Autowired to work, the following also needs to be added to the config file

Xml code

 

 

  1. <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />   

 

2. @Qualifier annotation

@Autowired is autowired based on type. For example, if there is more than one bean of type UserDao in the Spring context, a BeanCreationException will be thrown; if there is no bean of type UserDao in the Spring context, a BeanCreationException will also be thrown. We can use @Qualifier with @Autowired to solve these problems. as follows:

1). There may be multiple instances of UserDao

Java code

 

 

  1. @Autowired       
  2. @Qualifier("userServiceImpl")         
  3. public IUserService userService;  

 

or

Java code

 

 

  1. @Autowired       
  2. public void setUserDao(@Qualifier("userDao") UserDao userDao) {        
  3.     this.userDao = userDao;        

 

In this way, Spring will find the beans with id userServiceImpl and userDao for assembly.

2). There may not be an instance of UserDao

Java code

  1. @Autowired(required = false)        
  2. public IUserService userService;    

 

3. @Resource annotation

JSR-250 standard annotation, it is recommended to use it instead of Spring's proprietary @Autowired annotation. The role of @Resource is equivalent to @Autowired, except that @Autowired is automatically injected according to byType, while @Resource is automatically injected according to byName by default. @Resource has two important attributes, namely name and type. Spring parses the name attribute of the @Resource annotation as the name of the bean, and the type attribute parses it as the type of the bean. So if the name attribute is used, the automatic injection strategy of byName is used, and the automatic injection strategy of byType is used when the type attribute is used. If neither the name nor the type attribute is specified, the strategy will be automatically injected using byName through the reflection mechanism. For @Autowired to work, the following also needs to be added to the configuration file:

Xml code

 

 

  1. <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> 

 

@Resource assembly order:

a. If both name and type are specified, the only matching bean will be found from the Spring context for assembly, and an exception will be thrown if not found

b. If name is specified, look for a bean with a matching name (id) from the context for assembly, and throw an exception if it is not found

c. If type is specified, the only bean with matching type is found from the context for assembly, if not found or more than one is found, an exception will be thrown

d. If neither name nor type is specified, it will be assembled automatically according to the byName method (see 2); if there is no match, it will fall back to a primitive type (UserDao) for matching, and if it matches, it will be automatically assembled;

4. @PostConstruct (JSR-250) annotation

Add the annotation @PostConstruct to the method, and this method will be executed by the Spring container after the bean is initialized (Note: Bean initialization includes, instantiating the bean, and assembling the properties of the bean (dependency injection)). A typical application scenario of it is when you need to inject a property defined in its parent class into a bean, and you cannot override the parent class property or property setter method, such as:

Java code

 

 

  1. public class UserDaoImpl extends HibernateDaoSupport implements UserDao {        
  2.     
  3.     private SessionFactory mySessionFacotry;        
  4.     
  5.     @Resource    
  6.     public void setMySessionFacotry(SessionFactory sessionFacotry)     
  7.     {        
  8.         this.mySessionFacotry = sessionFacotry;        
  9.     }        
  10.     
  11.     @PostConstruct       
  12.     public void injectSessionFactory()     
  13.     {        
  14.         super.setSessionFactory(mySessionFacotry);        
  15.     }     
  16. }  

 

Here, through @PostConstruct, a sessionFactory private property defined in the parent class of UserDaoImpl is injected into our own sessionFactory (the setSessionFactory method of the parent class is final and cannot be overridden), and then we can call super.getSessionFactory() to get access this property.

5. @PreDestroy (JSR-250) annotation

Add the annotation @PreDestroy to the method, and this method will be executed by the Spring container after the bean is initialized. Its usage is the same as @PostConstruct. The difference from @PostConstruct is that the methods annotated with @PostConstruct will be called after the class is instantiated, while the methods annotated with @PreDestroy will be called before the class is destroyed.

6. @Component annotation (deprecated)

Just add a @Component annotation to the corresponding class to define the class as a Bean. Spring also provides more detailed annotation forms: @Repository, @Service, @Controller, which correspond to storage layer beans, business layer beans, and presentation layer beans, respectively. In the current version (2.5), these annotations have the same semantics as @Component and are completely generic. More semantics may be added to them in future versions of Spring. Therefore, we recommend using @Repository, @Service, @Controller instead of @Component.

7. @Scope annotation

When using XML to define beans, we may also need to define the scope of a bean through the scope attribute of the bean. We can also use the @Scope annotation to complete this work:

Java code

  1. @Scope("session")        
  2. @Component()        
  3. public class UserSessionBean implements Serializable{      
  4.  ... ...     
  5. }  

 

2. Configuration enable annotation (note that the following configuration requires the use of spring2.5 header files, which is not applicable in spring3.0)

1. Use simplified configuration

Spring 2.1 adds a new context schema namespace, which provides convenient configuration for annotation-driven, property file import, load-time weaving and other functions. We know that the annotation itself doesn't do anything, it only provides metadata information. For metadata information to really work, the processors responsible for handling that metadata must work.

AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor are the processors that process these annotation metadata. But defining these beans directly in the Spring configuration file is clumsy. Spring provides us with a convenient way to register these BeanPostProcessors, that is, the following is the configuration of spring.

Xml code

 

 

  1. <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"       
  2.     xsi:schemaLocation="http://www.springframework.org/schema/beans        
  3.     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd        
  4.     http://www.springframework.org/schema/context        
  5.     http://www.springframework.org/schema/context/spring-context-2.5.xsd">        
  6.     <context:annotation-config />        
  7. beans>  

 

will be implicitly registered with the Spring container

AutowiredAnnotationBeanPostProcessor 、

CommonAnnotationBeanPostProcessor 、

PersistenceAnnotationBeanPostProcessor

RequiredAnnotationBeanPostProcessor

These 4 BeanPostProcessors.

2. Use the Let Bean Definition Annotation to Work

Xml code

 

 

  1. <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"       
  2.     xsi:schemaLocation="http://www.springframework.org/schema/beans        
  3.     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd        
  4.     http://www.springframework.org/schema/context        
  5.     http://www.springframework.org/schema/context/spring-context-2.5.xsd">        
  6.     <context:component-scan base-package="com.kedacom.ksoa" />        
  7. beans>   

 

Here, all configuration content that defines beans through elements has been removed, and only one line of configuration needs to be added to solve all problems - Spring XML configuration files have been extremely simplified (of course configuration metadata is still required, but in the form of comments exists). The base-package attribute specifies the class package to be scanned. All classes in the class package and its recursive subpackages will be processed.

It also allows to define 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

Annotations | org.example.SomeAnnotation | Filter out all classes annotated with SomeAnnotation

class name specified | org.example.SomeClass | filter the specified class

regex | com\.kedacom\.spring\.annotation\.web\..* | filter some classes by regex

AspectJ Expression | org.example..*Service+ | Filter some classes by AspectJ expression

Taking regular expressions as an example, I list an application example:

Xml code

  1. <context:component-scan base-package="com.casheen.spring.annotation">        
  2.     <context:exclude-filter type="regex" expression="com\.casheen\.spring\.annotation\.web\..*" />        
  3. context:component-scan>    

 

 

 

 It is worth noting that the configuration item not only enables the function of scanning class packages to implement annotation-driven bean definitions, but also enables the function of annotation-driven automatic injection (that is, it also implicitly registers AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor internally), so when After use, it can be removed.

3. 
Spring's @Transcation and EJB's Spring's @Transactional or EJB3's @TransactionAttribute annotation are not supported. Use this configuration to achieve the goal.

4. 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 scope attribute of the bean. We can also use the @Scope annotation to complete this work:

Java code

 

    1. @Scope("session")           
    2. @Component()            
    3. public class UserSessionBean implements Serializable {            
    4.     ...           
    5. }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325204518&siteId=291194637