On the Java reflection principle with SpirngIOC

What's in Java reflection?

JAVA reflection mechanism is in the operating state, for any class, are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; this information acquired dynamically and dynamic invocation a method of object function called reflection mechanism java language.

It means in the JVM run-time, dynamic program can get all the information of a class. Java object role is accessed by reflection properties, methods, construction method and the like;

Java reflection mechanism usage scenarios

The most classic is the JDBCload drivers Class.forName(... ...);
and Springof IOC, as well as to use more or less reflected in a lot of the framework.

SpringIOC

SpringIOCThe emergence of liberation in a newway to get the object, the relationship between each of the bean (entity classes) and bean (the entity) to a third party container management. The traditional Springproject, a xmlfashion statement as a configuration file Beanand then through the 容器.getBean("one");acquisition target.

Thinking: SpringIOCthe underlying implementation idea is kind of how?

Traditional Springproject using the XMLconfiguration file, which defines a number of statements Bean, we look at XMLthe file Beanstructure that contains the Classattributes idproperty.
Here Insert Picture Description
The core idea is to instantiate reflection Bean, it is to obtain the final container .getBean (String bean) manner to an object. Reflecting only need to be able to instantiate the class path of the target object, but the properties are already stored in the xmlconfiguration file, so we need to use xmlanalytical techniques to read xmlfiles.

We first customize a container object, a container object contains a private property path, as the structure of the object to the Senate, this path represents the path of the project. Then create a getBean(String beanId)method.

Roughly Code:

// 容器对象
public class MyXMLContext {
	private String xmlPath;

	public MyXMLContext(String xmlPath) {
		this.xmlPath = xmlPath;
	}

	public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, NoSuchFieldException,
			SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException {

		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(this.getClass().getClassLoader().getResourceAsStream(xmlPath));
		Element rootNode = document.getRootElement();
		List<Element> childElements = rootNode.elements();
		Object bean = null;
		for (Element child : childElements) {
			String xmlbeanId = child.attributeValue("id");
			if (!beanId.equals(xmlbeanId)) {
				continue;
			}
			String beanClassPath = child.attributeValue("class");
			Class<?> forName = Class.forName(beanClassPath);
			bean = forName.newInstance();
			List<Element> e = child.elements();
			for (Element element : e) {
				String name = element.attributeValue("name");
				String value = element.attributeValue("value");
				Field field = forName.getDeclaredField(name);
				field.setAccessible(true);
				field.set(bean, value);
			}
		}
		return bean;
	}

	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
			IllegalArgumentException, IllegalAccessException, InstantiationException, DocumentException {
		MyXMLContext appLication = new MyXMLContext("user.xml");
		Object bean = appLication.getBean("darian");
		UserEntity user = (UserEntity) bean;
		System.out.println(user.toString());
	}

}
// 实体类对象,省略了get/set/toString及构造方法
public class UserEntity {
	private String userId;
	private String userName;
}
// xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="darian" class="entity类路径">
		<property name="userId" value="1"></property>
		<property name="userName" value="小明"></property>
	</bean>
	<bean id="coco" class="entity类路径">
		<property name="userId" value="2"></property>
		<property name="userName" value="小红"></property>
	</bean>
</beans>

Summarizes the SpringIOCunderlying implementation principles:

  1. Reads the XMLconfiguration file
  2. According to beanIdlocate beanconfiguration, and obtain profile classaddress
  3. Using the Javareflection technique instantiate an object
  4. Get property configuration using a reflection technique assignment

For more details:

  1. Use of the incoming parameter acquisition xmlstream file and using dom4jparsed into Documentobjects
  2. For Documentobtaining the root element of the object subject <beans>to the following tag traverse, it determines whether there is matching id.
  3. If you find the corresponding idequivalent to find an Elementelement, we began to create objects, to acquire classproperty, create an object based on property values by the reflection.
  4. Traversing <bean>the label propertytab, and the attribute assignment. Note that requires separate treatment int, floattype of property, because in xmlthe configuration of these attributes are configured in the form of a string, thus requiring additional treatment.
  5. If the property propertytag has refthe attribute, the value of a property is described an object, in accordance with id( refto obtain the value of the property) refcorresponding to the object, to give attribute assignment.
  6. Returns the object created, if no corresponding idor <beans>not the sub-tab returnsnull

This is SpringIOCroughly a realization of the idea, but now most are already using the SpringBootproject uses annotations @Autowiredway.

About notes in this regard will continue to follow ...

Published 13 original articles · won praise 32 · views 10000 +

Guess you like

Origin blog.csdn.net/QingHe97/article/details/103827464