1. Using spring annotations to inject properties
1.1. How we injected 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"
Com.kedacom.spring.annotation.persistence.UserDaoImpl ">
<property name=" sessionfactory "ref=" Mysessionfactory "/>
</bean>
1.2. Introduction of @autowired annotation (not recommended, recommended to use @resource)
the implementation of the class (callout the member variable)
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 annotate member variables, methods, and constructors to accomplish automatic assembly work. In the two different implementations, @Autowired are labeled differently, and they will automatically assemble Userdao this property when spring initializes Usermanagerimpl this bean, the difference being: in the first implementation, Spring directly assigns the only one bean of the Userdao type to the Userdao member variable; in the second implementation, spring invokes the Setuserdao method to assemble the Userdao type's unique bean into the Userdao attribute.
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, Also throws a Beancreationexception exception. We can use @qualifier with @autowired to solve these problems.
1. There may be multiple instances of Userdao
@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) {
This.userdao = Userdao;
}
1.5. @Resource (JSR-250 standard annotation, recommended to use it instead of the spring proprietary @autowired annotation)
Spring supports not only its own defined @autowired annotations, but also several annotations defined by the JSR-250 specification, namely, @resource, @PostConstruct, and @predestroy.
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 is used to automatically inject the policy through the reflection mechanism.
@Resource Assembly Order
If 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
If name is specified, an exception is thrown if the bean that matches the names (IDs) in the context is assembled and cannot be found
If type is specified, an exception is thrown when a unique bean from the context is found to be assembled, not found or multiple
If name is not 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 the match is made;
1.6. @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;< c3/> @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 ().
1.7. @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.
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 introductions, load-time weaving, and more. We know that the annotation itself is not going to do anything, it only provides meta data information. For the metadata information to really work, the processors responsible for processing the metadata must be working.
Autowiredannotationbeanpostprocessor and Commonannotationbeanpostprocessor are the processors that process these annotation metadata. However, it is awkward to define these beans directly in the spring configuration file. 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 with the spring container autowiredannotationbeanpostprocessor, Commonannotationbeanpostprocessor, Persistenceannotationbeanpostprocessor and Requiredannotationbeanpostprocessor these 4 beanpostprocessor.
2. 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.
2.1. @Component (not recommended), @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 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.
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 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
Take the regular expression as an example, I enumerate an application instance:
<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 worth noting that <context:component-scan/> configuration entries enable the ability to scan the class pack to implement annotation-driven bean definitions. Note-driven automatic injection is also enabled (that is, autowiredannotationbeanpostprocessor and Commonannotationbeanpostprocessor are implicitly registered internally), so when using the < 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 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 {
...
}
3. Defining the relationship between three beans before using annotation is this
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 the autowired to annotate , he can be the member variable, method and constructor standard, complete automatic assembly work.
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=" 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 beanpostprocessor will automatically function to automatically inject the Bean labeled @Autowired--> <bean class= "Org.springframework.bean S.factory.annotation. Autowiredannotationbeanpostprocessor "/> <!--remove the information from the boss Bean's property injection configuration--> <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" > <p
Roperty name= "brand" value= "Red flag CA72"/> <property name= "price" value= "Mark"/> </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 not finding the bean-times error.
When there are multiple candidate beans, we can specify the name of the injected bean through the @qualifier annotation.
@Autowired and @Qualifier are used in combination, the automatic injection strategy is transformed from Bytype to ByName. @Autowired can annotate member variables, methods, and constructors, while @Qualifier annotation objects are member variables, method arguments, constructor arguments. Because of the differences in annotation objects, Spring does not unify @Autowired and @Qualifier into one annotation class.
5. The @resorce is reflected by the name, and he has two parameters, name and type, which are mapped using name by ByName, and using type to map according to Bytype.
Package Com.baobaotao;
Import Javax.annotation.Resource;
The public class Boss {
//automatically injects a Bean of type car to
@Resource private car car
;
Automatically inject a bean @Resource (name = Office) with the bean name called Office
Private Office office;
@postconstructor and predestory are used to annotate the methods of class initialization and before it 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");
}
..
}
6. @compent can define beans directlyso that you do not need to configure the bean in the XML configuration file
Package Com.baobaotao;
Import org.springframework.stereotype.Component;
@Component public
class Car {
...
}
Package Com.baobaotao;
Import org.springframework.stereotype.Component;
@Component public
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;
..
}
@Component have an optional entry parameter that specifies the name of the bean, and in the boss, we define the bean name as "Boss". Typically, beans are singleton, and the place where the bean needs to be injected is automatically injected by the Bytype policy, so you don't have 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>
7. @scope can be used to specify its objectives
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: @Repository, @Service, and @Controller. In the current Spring version, these 3 annotations are equivalent to @Component, but from the naming of annotation classes 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. While these 3 annotations are nothing new than @Component, Spring will add special features to them in future releases. So, if a WEB application uses a classic three-tiered hierarchy, it's best to annotate the classes in the persistence layer, business layer, and control layer with @Repository, @Service, and @Controller, and use the @Component Comment on those classes that are more neutral.