问题描述
当我需要使用Property Place Holder时,只需按如下所示在spring_config.xml中定义一个bean,而无需在Java代码中对该bean做任何事情,spring怎么会知道呢?
When I need to use Property Place Holder, I just define a bean in spring_config.xml as follows, without doing anything to this bean in java code, how could the spring know that?
<bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="spring_test/spring.properties"></bean>
另一个令人困惑的部分是相似的:我在spring_config.xml中定义了两个Bean,即SqlSessionFactoryBean和MapperFactoryBean,如何在无需编写任何Java代码的情况下实现MapperFactoryBean就像我的DAO的代理一样?
another confused part is alike: I define two beans in spring_config.xml, namely SqlSessionFactoryBean and MapperFactoryBean, how could spring implement that the MapperFactoryBean acts just like a proxy to my DAO without I having to write any java code?
是否有任何有关xml解析机制或相关内容的文章?非常感谢!
Is there any article on the mechanism of xml parsing or something related? Thanks a lot!
推荐答案
您需要了解Java Reflection.Java Reflection使得在运行时检查类,接口,字段和方法成为可能,而无需在编译时知道类,方法等的名称.还可以使用反射实例化新对象,调用方法并获取/设置字段值.下面是一个简单的示例.
You need to know about Java Reflection.Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.below is simple example.
package com.example;
public class Emplyoee {
private String name;
public Emplyoee() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String args[]) {
String className = "com.example.Emplyoee";
try {
//finds class, casts Emplyoee class
Class<Emplyoee> klass = ((Class<Emplyoee>) Class.forName(className ));
//instantiate new objects,notice Emplyoee class
Emplyoee theNewObject = klass.newInstance();
//set value
theNewObject.setName("john");
//calls "name" by getter method,and prints "john"
System.out.println(theNewObject.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Spring容器将通过"forName"方法找到"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"类,并实例化"PropertyPlaceholderConfigurer"类.
The Spring container will find "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" class by "forName" method and instantiate "PropertyPlaceholderConfigurer" class.
这篇关于在程序生命周期中,春季的xml机制是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!