Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the parsing of annotation processing framework and source code implementation in spring

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

In this issue, the editor will bring you about the analysis of the annotation processing framework in spring and how the source code is implemented. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

The difference between @ Autowired and @ Resource:

Assemble with @ Autowired and @ Resource annotations in Java, which are:

1. @ Autowired assembles dependent objects according to the default type (class name). By default, it requires that dependent objects must exist. If null is allowed, you can set its required attribute to false

If we assemble by name, we can use it with the @ Qualifie annotation.

Such as:

@ Autowired @ qualifie ("personDaoBean")

Private PersonDaoBean personDaoBean

@ Resource assembles by default by name (name= "test"). The name can be set by @ resource's name attribute. When a bean matching the name is not found, it will be assembled by type.

Note: if the name property is not specified and the installation default name still cannot find the dependent object, @ Resource will fall back to assembling by type. But once the name attribute is specified, it can only be assembled by name.

The following example briefly illustrates the principle of spring annotations:

Realize the processing and parsing of annotations on set methods and field properties.

1. Definition notes

Java code

Package com.yt.annotation

Import java.lang.annotation.ElementType

Import java.lang.annotation.Retention

Import java.lang.annotation.RetentionPolicy

Import java.lang.annotation.Target

/ * *

* @ Description: define annotations

* @ ClassName: ZxfResource

* @ Project: spring-aop

* @ Author: zxf

* @ Date: 2011-6-7

, /

/ / execute at run time

@ Retention (RetentionPolicy.RUNTIME)

/ / where the comments apply (fields and methods)

@ Target ({ElementType.FIELD, ElementType.METHOD})

Public @ interface ZxfResource {

/ / name attribute of the comment

Public String name () default ""

}

2. Annotated service classes

Java code

Package com.yt.annotation

/ * *

* @ Description: annotated service

* @ ClassName: UserDaoImpl

* @ Project: spring-aop

* @ Author: zxf

* @ Date: 2011-6-7

, /

Public class UserServiceImpl {

Public UserDaoImpl userDao

Public User1DaoImpl user1Dao

/ / Note on the field, you can configure the name attribute

@ ZxfResource

Public User2DaoImpl user2Dao

/ / comments on the set method with the name attribute

@ ZxfResource (name = "userDao")

Public void setUserDao (UserDaoImpl userDao) {

This.userDao = userDao

}

/ / Note on the set method, name property is not configured

@ ZxfResource

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.")

}

}

3. DAO to be injected

Java code

Package com.yt.annotation

/ * *

* @ Description: the DAo class to be injected

* @ ClassName: UserDaoImpl

* @ Project: spring-aop

* @ Author: zxf

* @ Date: 2011-6-7

, /

Public class UserDaoImpl {

String name

Public void show () {

System.out.println ("here is the dao method.")

}

}

Xml code

4. Annotation processor

Java code

Package com.yt.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

/ * *

* @ Description: the principle of annotation in spring

* @ ClassName: ClassPathXMLApplicationContext

* @ Project: spring-aop

* @ Author: zxf

* @ Date: 2011-6-3

, /

Public class ClassPathXMLApplicationContext {

Logger log = Logger.getLogger (ClassPathXMLApplicationContext.class)

List beanList = new ArrayList ()

Map sigletions = new HashMap ()

Public ClassPathXMLApplicationContext (String fileName) {

/ / read the bean managed in the configuration file

This.readXML (fileName)

/ / instantiate bean

This.instancesBean ()

/ / Annotation processor

This.annotationInject ()

}

/ * *

* read Bean configuration file

* @ param fileName

* @ return

, /

@ SuppressWarnings ("unchecked")

Public void readXML (String fileName) {

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 beansList = beans.elementIterator ()

BeansList.hasNext ();) {

Element element = beansList.next ()

BeanDefine bean = new BeanDefine (

Element.attributeValue ("id")

Element.attributeValue ("class"))

BeanList.add (bean)

}

} catch (DocumentException e) {

Log.info ("error reading configuration file....")

}

}

/ * *

* instantiate Bean

, /

Public void instancesBean () {

For (BeanDefine bean: beanList) {

Try {

Sigletions.put (bean.getId ()

Class.forName (bean.getClassName ()) .newInstance ()

} catch (Exception e) {

Log.info ("error instantiating Bean...")

}

}

}

/ * *

* Annotation processor

* if the name attribute is configured in the annotation ZxfResource, the instance reference to be injected is obtained according to the name specified by the name.

* if the annotation ZxfResource; does not configure the name attribute, scan the configuration file according to the type to which the attribute belongs

* injected instance reference

*

, /

Public void annotationInject () {

For (String beanName:sigletions.keySet ()) {

Object bean = sigletions.get (beanName)

If (beanned null) {

This.propertyAnnotation (bean)

This.fieldAnnotation (bean)

}

}

}

/ * *

* handle comments added to the set method

* @ bean processed by param bean

, /

Public void propertyAnnotation (Object bean) {

Try {

/ / get the description of its attributes

PropertyDescriptor [] ps =

Introspector.getBeanInfo (bean.getClass (). GetPropertyDescriptors ()

For (PropertyDescriptor proderdesc: ps) {

/ / get all set methods

Method setter = proderdesc.getWriteMethod ()

/ / determine whether the set method defines annotations

If (setterless null & & setter.isAnnotationPresent (ZxfResource.class)) {

/ / get the current comment and determine whether the name attribute is empty

ZxfResource resource = setter.getAnnotation (ZxfResource.class)

String name = ""

Object value = null

If (resource.name ()! = nullboxes)! ".equals (resource.name () {

/ / get the content of the name attribute of the annotation

Name = resource.name ()

Value = sigletions.get (name)

} else {/ / if the name attribute is not specified in the current annotation, it is matched according to the type

For (String key: sigletions.keySet ()) {

/ / determine whether the type to which the current attribute belongs exists in the configuration file

If (proderdesc.getPropertyType (). IsAssignableFrom (sigletions.get (key). GetClass ()) {

/ / get instance objects with matching types

Value = sigletions.get (key)

Break

}

}

}

/ / allow access to the private method

Setter.setAccessible (true)

/ / inject reference objects into properties

Setter.invoke (bean, value)

}

}

} catch (Exception e) {

Log.info ("set method annotation parsing exception.")

}

}

/ * *

* handle comments on the field

* @ bean processed by param bean

, /

Public void fieldAnnotation (Object bean) {

Try {

/ / get all of its field descriptions

Field [] fields = bean.getClass () .getFields

For (Field f: fields) {

If (favored null & & f.isAnnotationPresent (ZxfResource.class)) {

ZxfResource resource = f.getAnnotation (ZxfResource.class)

String name = ""

Object value = null

If (resource.name ()! = nullboxes)! ".equals (resource.name () {

Name = resource.name ()

Value = sigletions.get (name)

} else {

For (String key: sigletions.keySet ()) {

/ / determine whether the type to which the current attribute belongs exists in the configuration file

If (f.getType (). IsAssignableFrom (sigletions.get (key). GetClass ()) {

/ / get instance objects with matching types

Value = sigletions.get (key)

Break

}

}

}

/ / allow access to the private field

F.setAccessible (true)

/ / inject reference objects into properties

F.set (bean, value)

}

}

} catch (Exception e) {

Log.info ("Field comment parsing exception.")

}

}

/ * *

* obtain the corresponding bean instance in Map

* @ param beanId

* @ return

, /

Public Object getBean (String beanId) {

Return sigletions.get (beanId)

}

Public static void main (String [] args) {

ClassPathXMLApplicationContext path = new ClassPathXMLApplicationContext (

"configAnnotation.xml")

UserServiceImpl userService = (UserServiceImpl) path.getBean ("userService")

UserService.show ()

}

}

This is what the editor shares with you in spring annotation framework parsing and source code implementation. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report