Spring automatic injection, using annotations to implement Spring basic configuration, Spring annotation QuickStart

Source: Internet
Author: User
Tags aop

Spring annotation

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


2.xml Configuration Work

<?xml version= "1.0" encoding= "GBK"?> <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" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema /context/spring-context-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframewor K.org/schema/aop/spring-aop-3.0.xsd Http://www.springframework.org/schema/tx Http://www.springframe Work.org/schema/tx/spring-tx-3.0.xsd "> <!--support annotations AspectJ--> <aop:aspectj-autoproxy/> <!-- Support Note Configuration Bean--> <context:annotation-config/> <!--use Annotation automatically registers the bean and checks the @required, @Autowired properties have been injected base-package the package that needs to be scanned (including all the child packages)--> <context:component-scan base-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 {<span     
style= "White-space:pre" >	</span>private sessionfactory mysessionfacotry;     
<span style= "White-space:pre" >	</span> @Resource    
<span style= "White-space:pre" >	</span>public void Setmysessionfacotry (Sessionfactory sessionfacotry) {     
    <span style= "White-space:pre" >		</span>this.mysessionfacotry = sessionfacotry;     
   <span style= "White-space:pre" >	</span>}     
  <span style= "White-space:pre" >	</span > @PostConstruct    
   <span style= "White-space:pre" >	</span>public void Injectsessionfactory () {     
      <span style= "White-space:pre" >		</span>super.setsessionfactory (mysessionfacotry);
   <span style= "White-space:pre" >	</span>}

Here, by @PostConstruct, a sessionfactory private attribute defined in the Userdaoimpl's parent class is injected into our own defined sessionfactory (the Setsessionfactory method of the parent class is fin AL, not reproducible), we can then access the property by calling Super.getsessionfactory ().
4. @PreDestroy (JSR-250)
With the annotation @PreDestroy on 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. The use of the same @PostConstruct.
5. Complete the bean definition using the spring annotation
We have described the features that are automatically injected into the bean by @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: Simply 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.


Original Blog Address: http://blog.csdn.net/vstar283551454/article/details/8683708


Although it is a turn, but there are problems can be interactive


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.