Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka
One, @Autowired annotations
Spring 2.5 introduces @Autowired annotations that allow you to annotate class member variables, methods, and constructors, and complete the task of automating Assembly. Use the @Autowired to eliminate the set, get method. Spring parses @Autowired with a beanpostprocessor, so @Autowired must be declared in the Spring container beforehand Autowiredannotationbeanpostprocessor Bean. Remove the original quoted <porpery > tags from the applicatoncontext.xml.
@Autowired is assembled by type by default, you must require that the dependent object must exist by default, and if you want to allow null values, you can set its Required property to False, for example: @Autowired (Required=false), If we want to use the name assembly can be used in conjunction with @qualifier annotations, as follows:
@Autowired () @Qualifier ("Basedao") private Basedao Basedao;
1) Annotate the collection
@Autowired (required=false) private list<user> userlist;
2) Annotation of the method
@Autowired @Qualifier ("user1") public void Add (user user) {System.out.println (user); }
Or
@Autowired public void Setuserdao (Userdao Userdao) {////For the setter method of the property this.userdao= Userdao;}
3) Annotation of the constructor function
@Autowired public Boss (car car, office office) {This.car = Car;this.office = Office }
4) Annotate the field
@Autowiredprivate Userdao Userdao;
When automatic injection is made using the @autowired annotation by default, the number of candidate beans matching in the spring container must be and only one. When a matching bean is not found, the spring container throws an Beancreationexception exception and indicates that at least one matching bean must be owned. When it is not possible to determine the bean in the spring container that must have a class, you can use @autowired (required=false) where you need to automatically inject the class bean, which is tantamount to telling spring that there is no error in finding a matching bean.
Of course, in general, where the use of @autowired is the need to inject beans, using automatic injection and allow non-injection is generally only encountered during the development period or test period (for example, in order to quickly start the spring container, only introduce some of the module spring configuration file), So @autowired (Required=false) is seldom used.
And there is no one type matching bean the opposite error is: If the Spring container has more than one candidate bean,spring container at startup will also throw a beancreationexception exception.
Second, @Qualifier annotations
@Autowired are automatically assembled according to the type. For example, if a bean of more than one Userdao type exists in the spring context, an 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. As follows:
1). Multiple Userdao instances may exist
Java code
- @Autowired
- @Qualifier ("Userserviceimpl")
- Public Iuserservice UserService;
Or
Java code
- @Autowired
- Public void Setuserdao (@Qualifier("Userdao") Userdao Userdao) {
- this. Userdao = Userdao;
- }
In this way, spring will find the bean with ID userserviceimpl and Userdao to assemble.
2). Userdao instances may not exist
Java code
- @Autowired (required = false)
- Public Iuserservice UserService;
@Autowired can comment on member variables, methods, and constructors, while @Qualifier label objects are member variables, method entry parameters, constructor arguments. The XX in @Qualifier ("XXX") is the name of the Bean, so when @Autowired and @Qualifier are used together, the auto-injected strategy changes from Bytype to ByName.
Third, @Resource annotations
JSR-250 standard annotations, it is recommended to replace spring's proprietary @autowired annotations. 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. @Resource There are two attributes that are more important, name and type,spring resolve 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.
1) Note on the field, byname
@Resource (name= "Userdao") private Userdao Userdao;
2) Comment on the method
@Resource public void Setuserdao (Userdao Userdao) {////For the setter method of the property this.userdao= Userdao;}
The role of the @Resource is equivalent to @autowired, except that @autowired is automatically injected by Bytype, and @resource by defaultByName automatic injection. @Resource There are two attributes that are important, the name and type,spring the Name property of the @resource annotation to the bean's name, and the type attribute to the Bean's. 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
1. If name and type are specified at the same time, the uniquely matched bean is found from the spring context to assemble, and an exception is thrown if it is not found
2. 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
3. If the type is specified, an exception is thrown when the unique bean matching the match is found in the context, cannot be found, or multiple occurrences are found
4. If neither name is specified and type is not specified, the assembly is automatically byname; if there is no match, the fallback is a match for the original type, and if the match is automatically assembled;
Iv. @Resource and @autowired use differences
@Resource (name= "Loginservice") private loginservice loginservice; @Autowired (Required=false) @Qualifier ("Loginservice") private Loginservice loginservice;
(1) [email protected] and @resource can be used to assemble beans. Can be written on a field, or written on a setter method;
(2) [email protected] By default assembly by type, by default must require that dependent objects must exist, if you want to allow null values, you can set
Set its Required property to false, such as: @Autowired (Required=false).
If we want to use the name assembly can be used in conjunction with @Qualifier annotations;
(3) [Email protected] (this annotation belongs to the Java EE), the default installation name is assembled, the name can be specified by the Name property, if not
The Name property is specified, and when the annotation is written on a field, the default Fetch field name is the installation name lookup if the annotation is written on the setter method by default
Name of the assembly. When a bean matching the name cannot be found, it is assembled by type. However, it is important to note that if the Name property once refers to the
will only be assembled by name.
v. @Scope annotations
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:
Java code
@Scope ("session") @Component () Public class Usersessionbean implements serializable{ ...
Or
@Repository ("User") @Scope ("prototype")//@Repository used to label the data Access component, DAO component//@Scope ("prototype") so that it returns a different instance each time. The default is singleton public class User {
vi. @PostConstruct (JSR-250) annotations
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 the bean into a parent class, and you cannot replicate the setter method of the parent class's property or property
Vii. @PreDestroy (JSR-250) Notes
By adding annotation @predestroy to the method, the method is executed by the spring container after the bean is initialized. Its usage is the same as @postconstruct. and @postconstruct Difference
In: @PostConstruct The annotation method is called after the class is instantiated, and the method that labels the @PreDestroy is called before the class is destroyed.
@PostConstructprivate void Init1 () {System.out.println ("execute int init1");} @PostConstructprivate void Init2 () {System.out.println ("execute int init2");} @PreDestroyprivate void Destory1 () {System.out.println ("execute int destory1");} @PreDestroyprivate void Destory2 () {System.out.println ("execute int destory2");}
The beans in the spring container are life-cycle, and spring allows specific operations to be performed after the bean has been initialized and before the bean is destroyed, either by implementing the Initializingbean/disposablebean interface to customize the initialization/ You can also specify an action method to be called after initialization/destruction by using the Init-method/destroy-method property of the <bean> element before destroying it. JSR-250 defines two annotation classes, @PostConstruct and @predestroy, that can only be applied to a method, after initialization/destruction of the previous method's designation. The method that labels the @postconstruct annotation is called after the class is instantiated, and the method that labels the @predestroy is called before the class is destroyed.
Viii. Examples of Use
Define User.java
Package Com.mucfc.model;public class User {string Name;int id;public string GetName () {return name;} public void SetName (String name) {this.name = name;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String toString () {return "name=" +name+ "id=" +id;}}
Define Userdao,java
Package Com.mucfc.dao;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.qualifier;import Org.springframework.stereotype.component;import Org.springframework.stereotype.controller;import Com.mucfc.model.User; @Componentpublic class Userdao {@ Autowired@qualifier ("user1") public void Add (user user) {System.out.println (user);}}
Where User1 has been defined in Beans.xml
Then there is:
Package Com.mucfc.service;import Java.util.list;import Javax.annotation.postconstruct;import Javax.annotation.predestroy;import Javax.annotation.resource;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.component;import Com.mucfc.dao.userdao;import Com.mucfc.model.User; @Componentpublic class MyComponent {@Autowired (required=false) Private list<user> userlist;public list<user> getuserlist () {return userlist;} @PostConstructprivate void Init1 () {System.out.println ("execute int init1");} @PostConstructprivate void Init2 () {System.out.println ("execute int init2");} @PreDestroyprivate void Destory1 () {System.out.println ("execute int destory1");} @PreDestroyprivate void Destory2 () {System.out.println ("execute int destory2");}}
Another:
Package Com.mucfc.service;import Javax.annotation.resource;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.component;import Org.springframework.stereotype.service;import Com.mucfc.dao.UserDao; @Component ("Service") public class Myserivce {@ Resource (name= "Userdao") Private Userdao userdao;public Userdao Getuserdao () {return Userdao;}}
Beans.xml
<?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:p= "http://www.springframework.org/schema/p " xmlns:context= "Http://www.springframework.org/schema/context" 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 "> <context:component-scan base-package=" COM.MUCFC "/> <bean id=" User " class= "Com.mucfc.model.User" p:name= "Evankaka" p:id= "0009"/> <bean id= "user1" class= " Com.mucfc.model.User "P:name=" Simle "p:id=" 456 "/> </beans>
The last is the test method:
Package Com.mucfc.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.mucfc.service.mycomponent;import Com.mucfc.service.myserivce;public class Test {public static void main (string[] args) {ApplicationContext context = new C Lasspathxmlapplicationcontext ("Beans.xml"); Myserivce service= Context.getbean ("service", Myserivce.class); MyComponent Mycomponent=context.getbean ("MyComponent", Mycomponent.class); System.out.println ("--------list--------"); for (int i = 0; i < mycomponent.getuserlist (). Size (); i++) { System.out.println (mycomponent.getuserlist (). get (i) ); } System.out.println (Service.getuserdao ()); ; ((classpathxmlapplicationcontext) context). Destroy ();}}
Output results
Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka
Note-based configuration bean of the "Spring" IOC (bottom)