Java programmers from the stupid bird to the rookie (72) in detail, Spring (iv) using annotations to implement spring basic configuration detailed

Source: Internet
Author: User


Note: Because I am not accustomed to annotation way, so after the annotation here to achieve the basic configuration, after the annotation will not be taken out alone to explain.


V: Spring Annotation

1. Preparatory work
(1) Import Common-annotations.jar
(2) Import schema file file name is Spring-context-2.5.xsd
(3) Configuring in the Beans node of XML


2.xml Configuration Work

<?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 "
default-default-lazy-init=" true ">
 <!--will configure the processor for annotations  -->   
 <context:annotation-config/>   
 <!-- Use annotation to define transactions-->
<tx:annotation-driventransaction-manager= "TransactionManager" Proxy-target-class = "true"/>
 <!--use annotation to automatically register beans and check @required, @Autowired properties have been injected base-package for packages that need to be scanned (including all child packages)-->
<context:component-scanbase-package= "com"/> ...   
 <beans>  


Note: <context:component-scan base-package= "*.*"/>
This configuration implicitly registers multiple processors that resolve annotations, such as:
Autowiredannotationbeanpostprocessor
Commonannotationbeanpostprocessor
Persistenceannotationbeanpostprocessor
Requiredannotationbeanpostprocessor
In fact, the annotation itself does not do anything, like XML, only play the role of configuration, mainly in the back of the powerful processor, which includes the <context:annotation-config/> configuration items used in the annotation of the processor, so configured < After the context:component-scanbase-package= "" >, no more Configuration <context:annotation-config>


1. Assemble in Java code using @autowired or @resource annotations, the difference being that the @Autowired by default by type, @Resource by default, when a name-matching bean is not found to be assembled by type.
The @Autowired is generally assembled on top of the set method, or it can be assembled at the top of the property, but is configured at the top of the attribute, destroying the Java encapsulation, so it is not recommended to use

@Autowired are automatically assembled according to the type. If there is more than one type of bean to be assembled in the spring context, a Beancreationexception exception is thrown, and if the type of bean to be assembled is not present in the spring context, Also throws a Beancreationexception exception. We can use @qualifier with @autowired to solve these problems.

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

In this way, spring will find the bean with ID userdao to assemble.

Userdao instance may not exist

@Autowired (required = false) public   
void Setuserdao (Userdao userdao) {   
    This.userdao = Userdao;   
}  


2. @Resource (JSR-250 standard annotation, recommended to use it instead of the spring proprietary @autowired annotation) spring supports not only @autowired annotations that are defined by itself, but also several annotations defined by the JSR-250 specification, They are @resource, @PostConstruct and @predestroy respectively.
The role of @Resource is equivalent to @autowired, but @autowired by Bytype automatic injection, and @resource by default by byname automatically injected Bale. It is important to have two properties @Resource, respectively, where name and type,spring resolve the Name property of the @resource annotation to the name of the bean, and the Type property resolves to the bean type. So if you use the Name property, you use the ByName automatic injection policy, and the Type property uses the Bytype automatic injection policy. If neither the name nor the type attribute is specified, the ByName automatic injection policy is used through the reflection mechanism
@Resource Assembly Order

1 if both name and type are specified, the unique matching bean is assembled from the spring context and the exception is thrown if it is not found

2 If name is specified, an exception is thrown when a bean that matches the names (IDs) in the context is assembled and cannot be found

3 If type is specified, a unique bean from the context found to be assembled, unable to find or found multiple, throws an exception

4 If neither name is specified nor type is 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;


3. @PostConstruct (JSR-250)
With annotation @postconstruct on the method, this method is executed by the spring container after the bean is initialized (note: The bean initialization includes, instantiating the bean, and assembling the Bean's properties (Dependency injection)).
A typical scenario for this is when you need to inject a property defined in a parent class into the bean, and you cannot copy the setter method of the 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, through @postconstruct, a sessionfactory private property defined for the parent class of Userdaoimpl, Injected into our own defined sessionfactory (the parent's Setsessionfactory method is final, not reproducible), then we can access the property by calling Super.getsessionfactory ().
4. @PreDestroy (JSR-250)
By adding annotation @predestroy to the method, this method is executed by the spring container after the bean is initialized. Since we do not currently need to use its scene, here is not to demonstrate. Its usage is the same as @postconstruct.
5. Complete the bean definition using the spring annotation
We have described the features that are automatically injected into the bean using @autowired or @resource, and we'll explain how to annotate the beans to completely remove the bean-defined configuration from the XML configuration file.
@Component: 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 at the beginning of lowercase. The bean name defined here is Userdaoimpl. You can also specify the name of the bean:
@Component ("Userdao")
@Component is a common form for all spring management components, and spring also provides a more granular form of annotations: @Repository, @Service, @Controller, which correspond to storage-tier beans, business-level 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 be appended with more semantics in future versions of spring. Therefore, we recommend the use of @repository, @Service, @Controller to replace @component.

6. 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.bzu "/>   
</ Beans>  




Here, all the configuration content that defines the bean through the <bean> element has been removed, and only one row of <context:component-scan/> configuration will be added to solve all the problems--spring The XML configuration file is extremely simplified (the configuration metadata is, of course, required, except 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 you to define filters to include or exclude certain classes under the base package. Spring supports the following 4 types of filtering:

· Filter Type Expression Example description

· Note Org.example.SomeAnnotation filters 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 through regular expressions

· AspectJ expression Org.example. *service+ filter Some classes by ASPECTJ expressions

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

@Scope (' session ')   
@Component () Public   
class Usersessionbean implements Serializable {   
    ...   
}  







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.