Implementation of annotation injection in spring (turn)

Source: Internet
Author: User

Recently in the spring of the source, look at one Leng Leng, good tired ....

When you see the IOC implementation, think about how to do this if you don't configure the attributes in XML. Look for information on the Internet, see a good.


Get to the point!

Assembled using @autowired and @resource annotations in Java, these two annotations are:
1. @Autowired to assemble dependent objects by default type (class name), by default it requires dependent objects to exist and, if allowed NULL, set its Required property to False
If we assemble by name, we can use it together with @qualifie annotations.
Such as:
@Autowired @qualifie ("Persondaobean")
Private Persondaobean Persondaobean;

@Resource is assembled by name (name= "test") by default, the name can be set by the @resource Name property, and the name-matching bean cannot be found to be assembled by type

Note: If you do not specify the Name property and the default name of the installation is still not found, the @Resource will fall back to assembly by type. However, once the name attribute is specified, it can only be assembled by name.



The following example briefly describes the spring annotation principle:

This example implements processing parsing for annotations on the set method and on the field properties. 1. Create an annotation

Package com.wuxing.learn.annotation;

Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

/** *
 @author wuxing
 * @date October 19, 2015 afternoon 5:04:40
 * * * *
/@Retention (Retentionpolicy.runtime)  
//Note applicable places (fields and methods)  
@Target ({elementtype.field, elementtype.method}) public 
@interface MyResource {
    //Note's Name property public  
    String name () default "";  
}

This annotation has only one attribute. Name


2. Create three Daoimpl.

Package Com.wuxing.learn.annotation.dao;

/**
 * @author wuxing
 * @date October 19, 2015 afternoon 5:11:31
 */public
class Userdaoimpl {
	String name;  
    
    public void Show () {  
        System.out.println ("Here is Dao method ...");  
    }  


Package Com.wuxing.learn.annotation.dao;

/**
 * @author wuxing
 * @date October 19, 2015 afternoon 5:12:24
 */public
class User1daoimpl {
	String name ;  
    
    public void Show1 () {  
        System.out.println ("Here is Dao1 method ...");  
    }  


Package Com.wuxing.learn.annotation.dao;

/**
 * @author wuxing
 * @date October 19, 2015 afternoon 5:12:44
 */public
class User2daoimpl {
	String name;  
    
    public void Show2 () {  
        System.out.println ("Here is Dao2 method ...");  
    }  


These three impl have only one method of printing.


3. Create a beandefine to store the class ID and class name.

Package com.wuxing.learn.annotation;

/**
 * @author wuxing
 * @date October 19, 2015 afternoon 5:18:49
 */public
class Beandefine {public

	String ID;
	Public String className;

	Public beandefine (string ID, string className) {
		this.id = ID;
		This.classname = ClassName;
	}

	Public String GetId () {return
		ID;
	}

	public void SetId (String id) {
		this.id = ID;
	}

	Public String GetClassName () {return
		className;
	}

	public void Setclassname (String className) {
		this.classname = className;
	}

}

4. Create a Serviceimpl.

Package com.wuxing.learn.annotation.service;

Import Com.wuxing.learn.annotation.MyResource;
Import Com.wuxing.learn.annotation.dao.User1DaoImpl;
Import Com.wuxing.learn.annotation.dao.User2DaoImpl;
Import Com.wuxing.learn.annotation.dao.UserDaoImpl;

/**
 * @author wuxing
 * @date October 19, 2015 afternoon 5:09:30
 */public

class Userserviceimpl {

	public Userdaoimpl Userdao;
	Public User1daoimpl User1dao;

	Note on the field, you can configure the Name property
	@MyResource public
	User2daoimpl User2dao;

	The annotation on the set method with the Name property
	@MyResource (name = "Userdao") public
	void Setuserdao (Userdaoimpl userdao) {
		This.userdao = Userdao;
	}

	The annotation on the set method does not configure the Name property
	@MyResource public
	void Setuser1dao (User1daoimpl user1dao) {
		This.user1dao = User1dao;
	}

	public void Show () {
		userdao.show ();
		User1dao.show1 ();
		User2dao.show2 ();
		System.out.println ("Here is the service method ...");
	}



The annotations on the field and the annotations of the set method are tested separately in the business layer.


5. Here is the configuration file configuration

<?xml version= "1.0" encoding= "UTF-8"?>  
<beans>  
    <bean id = "Userdao" Com.wuxing.learn.annotation.dao.UserDaoImpl "/>  
    <bean id =" User1dao "class=" Com.wuxing.learn.annotation.dao.User1DaoImpl "/>  
    <bean id =" User2dao "class=" Com.wuxing.learn.annotation.dao.User2DaoImpl "/>  
    <bean id =" UserService "class =" Com.wuxing.learn.annotation.service.UserServiceImpl "/>  
</beans>

The configuration only has the ID and the response class, if it is scanning range, there is no in-depth understanding.


6. Create a parsed class, the annotations in the demo are all implemented in this.

Package com.wuxing.learn.annotation;
Import Java.beans.Introspector;
Import Java.beans.PropertyDescriptor;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;

Import Java.util.Map;
Import Org.apache.log4j.Logger;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import org.dom4j.Element;

Import Org.dom4j.io.SAXReader;

Import Com.wuxing.learn.annotation.service.UserServiceImpl;
 /** * @Description: annotation principle in Spring * @ClassName: Classpathxmlapplicationcontext * @Project: SPRING-AOP * @author wuxing * @date October 19, 2015 PM 5:14:33 */public class Classpathxmlapplicationcontext {Logger log = Logger.getlogger (ClassPath

	Xmlapplicationcontext.class);
	list<beandefine> beanlist = new arraylist<beandefine> ();

	map<string, object> singletons = new hashmap<string, object> (); Public Classpathxmlapplicationcontext (String fileName) {//ReadTake the Bean this.readxml (fileName) that is managed in the configuration file;
		Instantiate the Bean This.instancesbean ();
	Note Processor This.annotationinject (); /** * Read Bean configuration file * @param fileName * @return/@SuppressWarnings ("unchecked") public void ReadXML (String fi
		Lename) {document document = NULL;
		Saxreader Saxreader = new Saxreader ();
			try {ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader ();
			Document = Saxreader.read (Classloader.getresourceasstream (fileName));
			Element beans = document.getrootelement (); for (iterator<element> beanslist = Beans.elementiterator (); Beanslist.hasnext ();)
				{element element = Beanslist.next ();
				Beandefine bean = new Beandefine (Element.attributevalue ("id"), Element.attributevalue ("class"));
			Beanlist.add (Bean);
		The catch (Documentexception e) {log.info ("Read profile error ..."); }/** * Instantiate bean/public void Instancesbean () {for (Beandefine bean:beanlist) {try {SINGLETONS.P UT (Bean.getid(), Class.forName (Bean.getclassname ()). newinstance ());
			catch (Exception e) {log.info ("Instantiate bean error ..."); }}/** * Annotation processor * If the annotation MyResource is configured with the Name property, the instance reference to be injected is obtained according to the names specified, * If the annotation myresource, and the Name property is not configured, it is scanned according to the type of attribute  File Fetch Instance Reference */public void Annotationinject () {for (String BeanName:singletons.keySet ()) {Object Bean =
			Singletons.get (Beanname);
				if (bean!=null) {this.propertyannotation (bean);
			This.fieldannotation (Bean); }}/** * Process annotations added in Set method * @param bean-processed bean/public void propertyannotation (Object bean) {try {//
			Gets the description of its properties propertydescriptor[] PS = Introspector.getbeaninfo (Bean.getclass ()). Getpropertydescriptors ();
				for (PropertyDescriptor proderdesc:ps) {//Get all Set Method setter = Proderdesc.getwritemethod (); 
					Determines whether the set method defines a callout if (Setter!=null && setter.isannotationpresent (myresource.class)) {//Gets the current annotation and determines whether the Name property is empty MyResource resource = setter.getannotation (MYresource.class);
					String name = "";
					Object value = null; if (Resource.name ()!=null&&! "".
						Equals (Resource.name ())) {//Get the content name = Resource.name () of the Name property of the annotation;
					Value = Singletons.get (name); }else{///If the current note does not specify a Name property, match by Type for (String Key:singletons.keySet ()) {//Determine if the type the current property belongs to exists in the configuration file if ( Proderdesc.getpropertytype (). IsAssignableFrom (Singletons.get (key). GetClass ()) {//Get type-matching instance object value = Sing
								Letons.get (key);
							Break
					}}//Allow access to private method setter.setaccessible (True); 
				Injecting the referencing object into the attribute Setter.invoke (bean, value);
		(Exception e) {Log.info ("Set method annotation Parse exception ..."););
			/** * Process annotations on field * @param bean/public void fieldannotation (Object bean) {try {//Get all of its field descriptions
			field[] fields = Bean.getclass (). GetFields (); for (Field f:fields) {if (F!=null && f.isannotationpresent (myresource.class)) {MyResource Resource = F.getannotation (Myresource.class);
					String name = "";
					Object value = null; if (Resource.name ()!=null&&! "".
						Equals (Resource.name ())) {name = Resource.name ();
					Value = Singletons.get (name); }else{for (String Key:singletons.keySet ()) {//Determine if the type that the current property belongs to exists in the configuration file if (F.gettype (). IsAssignableFrom (
								Singletons.get (Key). GetClass ()) {//Get type-matching instance object value = Singletons.get (key);
							Break
					}}//Allow access to private field f.setaccessible (true);
				Injecting the referencing object into the attribute F.set (bean, value);
		(Exception e) {log.info ("field annotation Parse exception ...").); /** * Gets the corresponding bean instance in the map * @param beanid * @return/Public Object Getbean (String beanid) {return Singl
	Etons.get (Beanid);
				public static void Main (string[] args) {classpathxmlapplicationcontext path = new Classpathxmlapplicationcontext (
		"Configannotation.xml"); Userserviceimpl UserService = (Userserviceimpl) Path.getbean ("UserService ");
	Userservice.show ();
 }
}

In the parsing process, it is through the reflection to get the field or the method, through the annotation to judge. Then inject them into fields and methods respectively.

Adhere to the spring source to understand ... Bite the bullet to see ah ...


All contents of this article are reproduced from http://zxf-noimp.iteye.com/blog/1071765

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.