1. Notes
Annotation is a mechanism similar to annotation. Adding annotations in the code can use this information at some time later. Unlike comments, comments are for us to see. The java virtual machine cannot compile, and the annotations are not compiled, but we can read the information in the annotations through the reflection mechanism. Annotation uses the keyword @interface, inherits java.lang.annotition.Annotation
1. Annotations in javaSE
Let me give you an example to review what annotation is in JavaSE. The key is two points: the definition of annotation and how to obtain the information above the annotation through reflection.
1. First define two annotations. One is annotated ClassInfo on the class, and the other is annotated 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, class files and runtime annotations @Documented //Can be generated in the help document public @interface ClassInfo { /** * This annotation has two properties of String type * @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 methods @Retention(RetentionPolicy.RUNTIME) //In java, class files and runtime annotations @Documented //Can be generated in help document public @interface MethodInfo { /** * This annotation has two properties of String type*/ String name() default ""; String value() default "";}2. Write an AnnotationUse class to use the annotation defined above
package com.itheima10.annotation;@ClassInfo(name="Xiaopingguo118",value="Niu")public class AnnotationUse { @MethodInfo(name="java",value="spring framework is important") public void java(){ }}3. Write the test class AnnotationTest and parse the properties 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 parse the annotation of the class, get Class * If parse the annotation of the method, get method first */ Class class1 = Itheima10.class; //Judge whether there is a ClassInfo annotation on the class if(class1.isAnnotationPresent(ClassInfo.class)){ //Get the annotation on the classClassInfo classInfo = (ClassInfo)class1.getAnnotation(ClassInfo.class); System.out.println(classInfo.value()); System.out.println(classInfo.name()); } Method[] methods = class1.getMethods(); for (Method method : methods) { //Is there a MethodInfo annotation on the method being traversed 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.
Using annotation programming is mainly 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 that I don’t use xml files, wouldn’t it violate the principle of opening and closing? It’s true. However, annotations are also good, so you don’t need to configure so many xml files when using annotations. The most important thing is that they have high development efficiency. .
When no annotations are used, many <bean> tags need to be configured in the configuration file applicationContext.xml file of the spring framework to declare class objects. Using annotations, you do not need to add tag pulls in the configuration file, and the corresponding description is to add instructions in the "comment" position of the corresponding class. The specific introduction is as follows:
•1. The combination of relationships between @Resource objects, the default is to assemble by name. If the associated object cannot be found based on the name, then the search by type will be continued. If no name attribute is specified,
• When the annotation is marked on a field, the default is to take the name of the field as the bean name to find the dependency object
• When the annotation is marked on the setter method of the attribute, the default attribute name is taken as the bean name to find the dependency object.
• Note: If the name attribute is not specified and the dependency object cannot be found by default, the @Resource annotation falls back to assembly by type. But once the name attribute is specified, it can only be assembled by name.
•2. @Autowired
@Autowired is assembled by type by default, @Resource is assembled by name by default, and only when a bean matching the name cannot be found will be assembled by type. The solution is to assemble dependent objects by type. By default, it requires dependent objects to exist. If null values are allowed, it can be set to false.
•3. @Qualifier
If we want to use assembly by name, we can use it in conjunction with the @Qualifier annotation.
1. To use annotations, you need to add namespace and constraint file steps to the configuration file:
Introducing context namespace
<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"
...
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
2. Add context:annotation-config tag to the configuration file
<context:annotation-config></context:annotation-config>
Example demonstration:
Write 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 says(){ this.student.say(); }}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
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- Put person and student into spring container--> <bean id="person"></bean> <bean id="student"></bean> <!-- Introduce context namespace xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" --> <!-- The annotation parser that has been injected since it was started --> <context:annotation-config></context:annotation-config></beans>
Write test class 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 to * <context:annotation-config></context:annotation-config> *, the annotation parser for dependency injection will be started* 4. The spring container will look up within the scope of the beans included in the spring management to see which properties of these classes are added with @Resource annotation* 5. If an attribute is added with @Resource annotation*, it will check whether the value of the name attribute of the annotation is "" * If it is "", it will match the name of the attribute where the annotation is located and the value of the id in the spring container. If the match is successful, the assignment * If the match is unsuccessful, the assignment will be performed according to the type. If the match is successful, the assignment will be assigned * If the match is unsuccessful, the assignment will be reported * If the match is unsuccessful, the assignment will be reported directly * If the match is not successful, the assignment will be reported * If the match is not successful, the assignment will be reported directly * If the match is not successful, the assignment will be reported * If the match is not successful, the assignment will be reported directly * Description: Annotations can only be used to compare the reference type xml and annotations. The efficiency is relatively high. Writing is more troublesome. Writing annotations is relatively simple and less efficient* */public class AnnotationTest { @Test public void testAnnotation(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (Person)context.getBean("person"); person.say(); }}If you use annotations, you don't need to load person and student in the configuration file, which can simplify the writing of the configuration file.
3. Scan
In the previous examples, we used XML bean definition to configure components. In a slightly larger project, there are usually hundreds of components. If these components are configured using the xml bean definition, it will obviously increase the size of the configuration file, making it not very convenient to find and maintain. spring2.5 introduces an automatic component scanning mechanism for us, which can find classes annotated with @Component, @Service, @Controller, and @Repository annotations under the classpath, and incorporate these classes into the spring container to manage. Its function is the same as using bean node configuration components in an XML file. To use the automatic scanning mechanism, we need to open the following configuration information:
1. Introduce context namespace
Add context:component-scan tag in xml configuration file
Where base-package is the package (subpackage) that needs to be scanned.
Example:
The above example is written in a scan mode as follows
@Componentpublic class Person { @Resource(name="student") private Student student; public void says(){ this.student.say(); }}@Componentpublic class Student { public void say(){ System.out.println("student"); }}applicationContext.xml only needs to be configured in one sentence
<!-- component component puts a class into a spring container, and the class is called scanning the component under the package and subpackage specified by base-package--> <context:component-scan base-package="com.itheima10.spring.scan"></context:component-scan>
Write test class AnnotationTest
/** * Principle* 1. Start spring container* 2. Spring container parsing* <context:component-scan base-package="com.itheima10.spring.scan"> </context:component-scan> 3. Scan in the packages and subpackages specified by base-package to see which classes contain @Component annotation 4. If there is this annotation @Component public class Person { } ==Equivalent to <bean id="person"> @Component("aa") public class Person { } ==Equivalent to <bean id="aa"> 5. Follow the analysis steps of @Resource: The entire process is scanned twice, the efficiency is getting lower and lower, and the writing is getting easier and easier* * */public class AnnotationTest { @Test public void testAnnotation(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (Person)context.getBean("person"); person.say(); }}Reappearance of instances
We will change the last document management system in Item51 in annotation. The Document interface remains unchanged, with read and write methods. The implementation classes are as follows ExcelDocument, PDFDocument, 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
<context:component-scan base-package="com.itheima10.spring.iocdi.document">
</context:component-scan>
Write a 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. Introduction to other annotation functions
@Service is used to annotate business layer components and service layer annotations
@Controller is used to annotate control layer components (such as action in struts) and control layer annotation
@Repository is used to annotate data access components, i.e. DAO components. Persistence layer annotation
@Component refers to components. When components are not easy to classify, we can use this annotation to annotate.
Examples reproduce MVC case
We review the MVC cases in Item51 again, adding the Dao, Service, and Action layers of PersonDaoImpl, PersonAction, and PersonServiceImpl respectively to add annotations to the Dao, Service, and Action layers of PersonDaoImpl.
@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 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 attribute inheritance.
1. Class inheritance
Spring properties:
(1) abstract: If set to true, it means that the defined bean is abstract, tell spring not to instantiate the bean;
Question: Must it be an abstract class? Could it be an abstract class?
(2) parent: indicates the function of the bean's id on the bean, which is equivalent to the function of extends on the java class;
Scene: There are three beans:
<bean id = "bean1" class = "…TestBean"> <property name="sex" value="male"/> </bean> <bean id = "bean2" class = "…TestBean"> <property name="sex" value="male"/> </bean> <bean id = "bean3" class = "…TestBean"> <property name="sex" value="female"/> </bean>
Modify: define spring parent bean
<bean id ="BaseBean" class ="…TestBean"> <property name="sex" value="male"/> </bean>
Define subbeans
<bean id ="bean1" parent = "BaseBean"/> Inherit the properties of the parent bean<bean id ="bean2" parent = "BaseBean"/> <bean id ="bean3" parent = "BaseBean"> Overwrite the properties of the parent bean<property name="sex" value="female"/> </bean>
Child beans can inherit the properties of the parent bean or override the properties of the parent bean.
2. Attribute inheritance
There are the same attributes between several different beans, and the scene can be extracted:
<bean id = "bean1" class = "…ATestBean"> <property name="sex" value="male"/> <property name="task" ref="task"/></bean><bean id = "bean2" class = "…BTestBean"> <property name="sex" value="male"/></bean>
Modify: (1) Extract public attributes
<bean id = "baseSex" abstract="true"> <property name="sex" value="male"/> </bean>
(2) Bean modification
<bean id = "bean1" class = "…ATestBean" parent="baseSex"> <property name="task" ref="task"/> </bean> <bean id = "bean2" class = "…BTestBean" parent="baseSex"/>
Here the bean has both parent and class attributes, and the baseSex pointed to by parent is to allow different beans to share the same attribute value; when the TransactionProxyFactoryBean declares the service, the inheritance of the bean attribute can significantly reduce the redundant xml configuration.
Annotation-based inheritance does not require parent attributes.
Let's have a small summary picture last
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.