I. Annotations
annotation annotation is an annotation-like mechanism that adds annotations to your code to be used at a later time. Unlike annotations, annotations are for us, the Java virtual machines are not compiled, annotations are not compiled, but we can read the information in the annotations through the reflection mechanism. Annotations Use the keyword @interface to inherit java.lang.annotition.Annotition
1, the annotation in the Javase
First, for example, to review what the annotation is in javase, the key is two points, the definition of the annotation and how to get the information from the annotation by reflection.
1. The first definition of two annotations is the annotation ClassInfo on the class, and the one on the method is annotated as MethodInfo.
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 class
@Retention (retentionpolicy.runtime)//in Java,class file and run-time annotations all work
@ Documented//can generate public
@interface ClassInfo {/** * in the Help document
the annotation has two string properties
* @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 method
@Retention (Retentionpolicy.runtime)//in Java,class file and run-time annotations all work
@Documented//can generate public
@interface MethodInfo {/** * in the Help document
the annotation has two string attributes */
string Name () default "";
String value () default "";
}
2. Write a class annotationuse to use the annotations defined above
Package com.itheima10.annotation;
@ClassInfo (name= "118", value= "NIU") public
class Annotationuse {
@MethodInfo (name= "Java", value= " Spring Framework is important ") public
void Java () {
}
}
3. Write test class Annotationtest, resolve the above two annotation attributes
Package com.itheima10.annotation;
Import Java.lang.reflect.Method;
Import Org.junit.Test;
public class Annotationtest {
the public static void Test () {
/**
* If the annotation of the class is parsed, first get the
annotation of class * If the method
*/
Class Class1 = Itheima10.class;
Determine if the class has ClassInfo annotations
if (class1.isannotationpresent (Classinfo.class)) {
//Get the annotations above the class
ClassInfo ClassInfo = (ClassInfo) class1.getannotation (classinfo.class);
System.out.println (Classinfo.value ());
System.out.println (Classinfo.name ());
}
Method[] methods = Class1.getmethods ();
For (methods Method:methods) {
//the method being traversed exists 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 capabilities.
Use annotation programming, primarily to replace XML files, and to make development faster. However, the use of XML files is to solve the modification of the program to modify the source code, and now do not use XML files, then do not violate the opening and closing principles, is indeed. However, annotations also have a good annotation, the use of annotations do not have to configure so many XML files, the most important is the development of high efficiency.
In the absence of annotations, the Spring Framework's profile Applicationcontext.xml file requires a lot of <bean> tags to be configured to declare class objects. With annotations, you do not have to add a label pull in the configuration file, which corresponds to adding a description in the comment location of the corresponding class. The details are as follows:
• 1. @Resource The combination of relationships between objects, by default, the assembly is by name, if the associated object is not found by name, then continue to find by type. If the Name property is not specified,
• When annotations are annotated on a field, that is, the name of the default Fetch field is used as the bean name to find the dependent object
• When the annotation is annotated on the setter method of the attribute, that is, by default, the property name is used as the bean name to find the dependent object.
• Note: If the Name property is not specified and the dependent object cannot be found by default, the @Resource annotation is rolled back to assembly by type. However, once the name attribute is specified, it can only be assembled by name.
2. @Autowired
@Autowired are assembled by type by default, @Resource by default, and when the name-matching bean is not found, it is assembled by type. The solution is to assemble the dependent object by type, which requires the dependent object to exist by default, and it can set the required property to False if the null value is allowed.
• 3, @Qualifier
If we want to use the assembly by name, we can use it together with @qualifier annotations.
1. Using annotations, you need to add namespaces and constraint file steps in the configuration file:
Introducing the 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 the context:annotation-config tag in the configuration file
<context:annotation-config></context:annotation-config>
Example Demo:
Write a person class with a student attribute and a say () method with the following code
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");
}
Configuring Applicationcontext.xml Files
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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 the person and student into the spring container--> <bean id= "Person class=" com.itheima10.s Pring.di.annotation.Person "></bean> <bean id=" student "class=" Com.itheima10.spring.di.annotation.Student "></bean> <!--Introducing the 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 "--> <!--initiated since the injection of the annotation parser--> <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 spring container * 2, instantiate person and student two beans * 3, when spring container resolves to * <context:annotation-config></cont Ext:annotation-config> * will start the dependency injection annotation parser * 4, the Spring container will look in the scope of the bean being incorporated into spring management to see which properties of these classes are added with @resource annotations * 5, If a @resource annotation is added to a property, it will see if the value of the Name property of the note is "* if" ", the name of the attribute that contains the note matches the value of the ID in the spring container, and if the match succeeds, the assignment * if the match is unsuccessful, follow
Type to match, match success assignment * If the match is unsuccessful, the error occurs * if not "", the value of the Name property of the note matches the value of the ID in the spring container, and if the match succeeds, the assignment * if the match is unsuccessful, the error is direct Note: Annotations can only be used to reference types XML is more efficient than annotation, and writing is more troublesome annotation writing is simpler and less efficient * * */public class Annotationtest {@T est public void testannotation () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcon
Text.xml ");
person who = (person) context.getbean (' person '); Person.say ();
}
}
If you use annotations, you do not need to load the person and student in the configuration file, which simplifies the authoring of your configuration files.
3, scanning
In the previous example, we used the XML bean definition to configure the component. In a slightly larger project, there are typically hundreds of components that, if configured with XML bean definitions, would obviously increase the size of the configuration file, and it would be inconvenient to find and maintain it. spring2.5 introduces a component automatic scanning mechanism, which can look for classes that annotate @component, @Service, @Controller, @Repository annotations under the CLASSPATH and incorporate these classes into the spring container for management. It works the same as using the Bean node configuration component in an XML file. To use the automatic scanning mechanism, we need to open the following configuration information:
1. Introducing the context namespace
Add a Context:component-scan tag to an XML configuration file
Where Base-package is the package (including the child package) that needs to be scanned.
Instance:
The above example is written in a scanned manner as follows
@Component public
class Person {
@Resource (name= "student")
private student student;
public void Say () {
this.student.say ();
}
}
@Component public
class Student {public
void say () {
System.out.println ("Student");
}
Applicationcontext.xml only need to configure a word
<!--the
component component puts
a class into the spring container, which is called a component that
scans--> <context under Base-package-specified packages and child packages
: Component-scan base-package= "Com.itheima10.spring.scan" ></context:component-scan>
Writing test class Annotationtest
/**
* Principle
* 1, start spring container
* 2, Spring container resolution
* <context:component-scan base-package= " Com.itheima10.spring.scan ">
</context:component-scan>
3, scanned in Base-package-specified packages and packets, See which classes contain @component Note 4 above
, if there is this annotation
@Component public
class Person {
}
= = = = equivalent to
<bean id= " Person "class=". Person ' >
@Component ("AA") public
class Person {
}
= = = equals
<bean id= "AA" class=. Person ">
5, according to the @resource analytical steps to implement the
instructions: The
entire process of scanning two times, less efficient, writing more and more simple
* *
/Public
Class Annotationtest {
@Test public
void Testannotation () {
ApplicationContext context =
New Classpathxmlapplicationcontext ("Applicationcontext.xml");
person who = (person) context.getbean (' person ');
Person.say ();
}
Instance representation
We will Item51 in the Final Document management system with the annotation method, the document interface is unchanged, there are read and write methods, implementation classes are as follows Exceldocument, Pdfdocument, 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>
Writing 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 function introduction
@Service used to annotate business layer components, service layer annotations
@Controller used to annotate control layer components (such as action in struts), control layer annotations
The @Repository is used to annotate the data Access component, the DAO component. Persistence layer Annotations
While @component refers to components, we can use this annotation to annotate when components are not properly categorized.
Instance Recurrence –mvc case
We revisit the MVC case in Item51, adding Persondaoimpl, Personaction, and Personserviceimpl dao,service,action layers with annotations
@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 property inheritance
1. Class inheritance
Spring Properties:
(1) Abstract: If set to true, indicates that the bean defined is abstract and tells spring not to instantiate the bean;
Question: Must it be an abstract class? Can it be an abstract class?
(2) Parent: Indicates the Bean's ID, its effect on the bean, which is equivalent to the role of extends for Java classes;
Scenario: 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>
modifying: Defining Spring Parent Bean
<bean id = "Basebean" class = "... Testbean ">
<property name=" sex "value=" male "/>
</bean>
Defining a child bean
<bean id = "Bean1" parent = "Basebean"/> inherits the properties of the parent bean
<bean id = "bean2" parent = "Basebean"/>
& Lt;bean id = "BEAN3" parent = "Basebean" > overwrite properties of parent bean
<property name= "Sex" value= "
female"/> </bean>
The child bean can inherit the properties of the parent bean, or it can overwrite the parent bean's properties
2. Property inheritance
The same properties exist between several different beans and can be drawn out
Scene:
<bean id = "Bean1" class = "... Atestbean "> <property name=" Sex "value=" male "/>" <property "task" name=
"task" ref=
< /bean>
<bean id = "BEAN2" class = "... Btestbean ">
<property name=" sex "value=" male "/>
</bean>
Modified: (1) Extract public properties
<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, where parent points to basesex to share the same property values between different beans; When Transactionproxyfactorybean declares the business, Bean property inheritance can significantly reduce the redundant XML configuration.
No parent attribute is required for annotations based inheritance.
A little summary of the last picture.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.