In-depth analysis of JavaWeb Item52 -- Spring Annotation
I. Annotations
Annotation is a mechanism similar to Annotation. You can add Annotation in the code to use this information at a later time. Different from annotations, annotations are for us. Java virtual machines do not compile and annotations are not compiled, but we can read the information in annotations through reflection mechanisms. Annotation uses the keyword @ interface to inherit java. lang. annotition. Annotition
1. annotations in javaSE
Let's take an example to review what annotation is in javaSE. The key is two points. The definition of annotation and how to get the annotation above through reflection.
1. Define two annotations first. One annotation is ClassInfo on the class, and the other annotation is MethodInfo on the method.
ClassInfo
Package com. itheima10.annotation; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; @ Target (ElementType. TYPE) // This annotation can be used on the class @ Retention (RetentionPolicy. RUNTIME) // in java, the class file and runtime annotation both work @ Documented // can be generated in the help document public @ interface ClassInfo {/*** This annotation has two String-type attributes * @ return */ string name () default ""; String value () default "";}
MethodInfo
Package com. itheima10.annotation; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; @ Target (ElementType. METHOD) // This annotation can be used on the METHOD @ Retention (RetentionPolicy. RUNTIME) // in java, the class file and runtime annotation both work @ incluented // generate public @ interface MethodInfo {/*** in the help document. This annotation has two String-type attributes */String name () default ""; String value () default "";}
2. Write an AnnotationUse class to use the annotation defined above
Package com. itheima10.annotation; @ ClassInfo (name = "Xiao Pingguo 118", value = "") public class AnnotationUse {@ MethodInfo (name = "java ", value = "spring framework is very important") public void java (){}}
3. Write the AnnotationTest test class and parse the attributes above the two annotations.
Package com. itheima10.annotation; import java. lang. reflect. method; import org. junit. test; public class AnnotationTest {public static void test () {/*** if the annotation of the parsing Class is obtained, first obtain the class * If the annotation of the parsing method, first obtain method */Class class1 = Itheima10.class; // judge whether there is ClassInfo annotation if (class1.isAnnotationPresent (ClassInfo. class) {// obtain the class above the annotation ClassInfo classInfo = (ClassInfo) class1.getAnnotation (ClassInfo. class); System. out. println (classInfo. value (); System. out. println (classInfo. name ();} Method [] methods = class1.getMethods (); for (Method method: methods) {// whether there is a MethodInfo annotation if (method. isAnnotationPresent (MethodInfo. class) {MethodInfo methodInfo = method. getAnnotation (MethodInfo. class); System. out. println (methodInfo. name (); System. out. println (methodInfo. value () ;}}@ Test public void test () {AnnotationTest. test ();}}
2. annotations in spring
The spring framework provides us with annotation functions.
Annotation programming is mainly used to replace xml files and make development faster. However, the use of xml files is to solve the problem of modifying the source code of the program. Now, if we do not use xml files, it does not violate the principle of opening/closing. However, annotations are well annotated, so you don't need to configure so many xml files when using annotations. The most important thing is high development efficiency ..
When annotations are not used, you need to configure a lot Label to declare class objects. If annotations are used, you do not need to add tags to the configuration file. The corresponding description is added to the "comment" position of the corresponding class. The details are as follows:
@ResourceThe combination of relationships between objects is assembled by name by default. If the associated objects cannot be found by name, the query continues by type. If the name attribute is not specified,
? When the annotation is marked on the field, that is, the field name is used as the bean name by default to find the dependent object
? When the annotation is marked on the property setter method, that is, the property name is used as the bean name by default to find the dependent object.
? Note: If the name attribute is not specified and the dependent object cannot be found according to the default name, the @ Resource annotation will be rolled back to assemble by type. However, once the name attribute is specified, it can only be assembled by name.
2.@Autowired <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Region/region + vD + region/region + M6GiIDxzdHJvbmc + PGNvZGU + region + vKudPDsLTD + region/region + DQo8cD7S/region/u/region = "brush: java; ">
2. Add the context: annotation-config tag to the configuration file.
Example:
Compile a Person class with a student attribute and a say () method. The Code is as follows:
Package com. itheima10.spring. di. annotation; import javax. annotation. resource; import org. springframework. beans. factory. annotation. autowired; import org. springframework. beans. factory. annotation. qualifier;/*** @ Autowired // match by type ** @ Autowired // match by type @ Qualifier ("student ") **/public class Person {@ Resource (name = "student") private Student student; public void say () {this. student. say ();}}
The Student class code is as follows:
package com.itheima10.spring.di.annotation;public class Student { public void say(){ System.out.println("student"); }}
Configure the applicationContext. xml file
Compile AnnotationTest
Package com. itheima10.spring. di. annotation; import org. junit. test; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext;/*** principle: * 1. Start the spring container * 2. instantiate the two beans "person" and "student" * 3. When the spring container is parsed *
* The dependency injection annotation parser is started. * 4. The spring container searches for the bean that is included in the spring management, check which attributes of these classes are added with @ Resource annotation * 5. If a property is added with @ Resource annotation *, check whether the name attribute value of this annotation is "" * if it is "", the name of the attribute where the annotation is located matches the id value in the spring container. If the matching is successful, the value is assigned * If the matching is unsuccessful, the matching is performed based on the type, if the matching succeeds, the value is assigned. * If the matching fails, an error is returned. * if it is not "", the value of the name attribute of the annotation matches the value of the id in the spring container, if the matching is successful, the value is assigned. * If the matching is unsuccessful, an error is reported. * Note: The annotation can only be used to compare the reference type xml with the annotation. xml is more efficient, it is easy to write annotation, and the efficiency is relatively low **/public class AnnotationTest {@ Test public void testAnnotation () {ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext. xml "); Person person = (Person) context. getBean ("person"); person. say ();}}
If annotations are used, you do not need to load the person and student in the configuration file, which simplifies the compilation of the configuration file.
3. Scanning
In the previous example, we used the bean definition of XML to configure components. In a slightly larger project, there are usually hundreds of components. If these components are configured using the bean definition of xml, it will obviously increase the size of the configuration file, and it is not easy to search and maintain. Spring2.5 introduces an automatic Component scanning mechanism. It can search for Classes marked with @ Component, @ Service, @ Controller, and @ Repository annotations under the class path, and add these classes to the spring container for management. It serves the same purpose as using bean node configuration components in xml files. To use the automatic scanning mechanism, we need to enable the following configuration information:
1. Introduce the context namespace
Addcontext:component-scanTag
WhereBase-packageThe package to be scanned (including the sub-package ).
Instance:
Write the preceding instance as follows:
@Componentpublic class Person { @Resource(name="student") private Student student; public void say(){ this.student.say(); }}
@Componentpublic class Student { public void say(){ System.out.println("student"); }}
Only one sentence is required for applicationContext. xml.
Compile AnnotationTest
/*** Principle * 1. Start spring container * 2. parse spring container *
3. Scan the specified package and package in the base-package, check which classes contain @ Component annotation 4. If the annotation @ Component public class Person {}== is equivalent to @ Component ("aa ") public class Person {}== is equivalent to 5. Follow the @ Resource parsing steps to perform instructions: the entire process is scanned twice, and the efficiency is getting lower and lower, writing is getting simpler **/public class AnnotationTest {@ Test public void testAnnotation () {ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext. xml "); Person person = (Person) context. getBean ("person"); person. say ();}}
Instance Reproduction
We will change the Document management system at the end of Item51 with the annotation method. The Document interface remains unchanged and there are read and write methods. The implementation classes are as follows: ExcelDocument, invalid Document, and WordDocument.
@Component("excelDocument")public class ExcelDocument implements Document{ public void read() { System.out.println("excel read"); } public void write() { System.out.println("excel write"); }}
@Component("pdfDocument")public class PDFDocument implements Document{ public void read() { System.out.println("pdf read"); } public void write() { System.out.println("pdf write"); }}
@Component("wordDocument")public class WordDocument implements Document{ public void read() { System.out.println("word read"); } public void write() { System.out.println("word write"); }}
DocumentManager
@Component("documentManager")public class DocumentManager { @Resource(name="excelDocument") private Document document; public void read(){ this.document.read(); } public void write(){ this.document.write(); }}
Configuration File
Compile the test class DocumentTest
public class DocumentTest { @Test public void testDocument(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); DocumentManager documentManager = (DocumentManager)context.getBean("documentManager"); documentManager.read(); documentManager.write(); }}
2. Other annotation Functions
@ ServiceUsed to mark service layer components and service layer annotations
@ ControllerUsed to mark control layer components (such as actions in struts) and control layer annotations
@ RepositoryIt is used to mark the data access component, that is, the DAO component. Persistent layer Annotation
@ Component refers to the Component. When the Component is difficult to classify, we can use this annotation for annotation.
Instance reproduction-MVC case
Let's review the MVC case in Item51, and add annotations to the Dao, Service, and Action layers of PersonDaoImpl, PersonAction, and PersonServiceImpl.
@Repository("personDao") public class PersonDaoImpl implements PersonDao { @Override public void savePerson() { System.out.println(" save person"); }}
@Service("personService")public class PersonServiceImpl implements PersonService{ @Resource(name="personDao") private PersonDao personDao; public void setPersonDao(PersonDao personDao) { this.personDao = personDao; } @Override public void savePerson() { this.personDao.savePerson(); }}
@Controller("personAction")public class PersonAction { @Resource(name="personService") private PersonService personService; public void setPersonService(PersonService personService) { this.personService = personService; } public void savePerson(){ this.personService.savePerson(); }}
Write and test MVCTest
public class MVCTest { @Test public void testMVC(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); PersonAction personAction = (PersonAction)context.getBean("personAction"); personAction.savePerson(); }}
4. Inheritance in spring
Spring supports inheritance, which can be divided into class inheritance and property inheritance.
1. class inheritance
Spring attributes:
(1) abstract: if it is set to true, the defined bean is abstract and spring is told not to instantiate the bean;
Question: Must it be an abstract class? Can it be an abstract class?
(2) parent: Specifies the bean id, which is equivalent to the function of extends for java classes;
Scenario: There are three beans:
<CODE class=" hljs applescript"> <BEAN id=bean1 class=……TestBean><BEAN> <property name="sex" value="male"></property> </BEAN> <BEAN id=bean2 class=……TestBean> <property name="sex" value="male"></property> </BEAN> <BEAN id=bean3 class=……TestBean> <property name="sex" value="female"></property> </BEAN></BEAN></CODE>
Modify: Define spring parent bean
<CODE class=" hljs applescript"> <BEAN id=BaseBean class=……TestBean><BEAN id=bean1 class=……TestBean> <property name="sex" value="male"></property> </BEAN></BEAN></CODE>
Define sub-Bean
<CODE class = "hljs applescript"> <BEAN id = bean1 parent = "BaseBean"> inherit attributes of the parent Bean <BEAN id = bean2 parent = "BaseBean"> </BEAN> <BEAN id = bean3 parent = "BaseBean"> overwrite the attributes of the parent Bean <property name = "sex" value = "female"> </property> </BEAN> </CODE>
The child bean can inherit the attributes of the parent Bean or overwrite the attributes of the parent Bean.
2. property inheritance
Several different beans have the same attributes and can be extracted.
Scenario:
<CODE class=" hljs applescript"><BEAN id=bean1 class=……ATestBean><BEAN id=bean1 parent="BaseBean"> <property name="sex" value="male"></property> <property name="task" ref="task"></property></BEAN><BEAN id=bean2 class=……BTestBean> <property name="sex" value="male"></property></BEAN></BEAN></CODE>
Modify: (1) extract public attributes
<CODE class=" hljs applescript"> <BEAN id=baseSex abstract="true"><BEAN id=bean1 class=……ATestBean> <property name="sex" value="male"></property> </BEAN></BEAN></CODE>
(2) bean Modification
<CODE class=" hljs applescript"> <BEAN id=bean1 class=……ATestBean parent="baseSex"><BEAN id=baseSex abstract="true"> <property name="task" ref="task"></property> </BEAN> <BEAN id=bean2 class=……BTestBean parent="baseSex"></BEAN></BEAN></CODE>
Here, the bean has both the parent and class attributes, and the parent points to the baseSex so that different beans share the same attribute values. When TransactionProxyFactoryBean declares the business, bean property inheritance can significantly reduce redundant xml configurations.
Annotation-based inheritance does not require the parent attribute.
The last small summary.