Posted on 2009-06-17 13:18
eric_xu 阅读(278)
评论(0) 编辑 收藏 所属分类:
J2EE
一个IoC的Demo程序
beans-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="helloBean" class="sjtu.rfid.HelloBean">
<property name="helloWord">
<value>Hello! Eric!</value>
</property>
</bean>
</beans>
SpringDemo.java
package sjtu.rfid;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class SpringDemo {
public static void main(String[] args){
ClassPathResource resource = new ClassPathResource("beans-config.xml");
BeanFactory factory = new XmlBeanFactory(resource);
HelloBean hello = (HelloBean) factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
ClassPathResource在指定classpath中寻找配置文件
resource为接口,有ClassPathResource,FileSystemResource,InputStreamResource,ServletContextRescource或UrlResource等,都可作为
XmlBeanFactory构造函数的参数,这儿为XML。BeanFactory管理不同形态的物件,可以是XML。
org.springframework.beans.factory.BeanFactory是Spring IoC容器的实际代表者,IoC容器负责容纳此前所描述的Bean,并对Bean进行管理。BeanFactory是IoC容器的核心接口,加载配置文件的方法:
1.Resource resource = new
FileSystemResource("beans-config.xml");
2.ApplicationContext context = new
ClassPathXmlApplicationContext(
new
String[] {"ApplicationContext.xml",
"ApplicationContext2.xml"});
BeanFactory factory = context;
HelloBean.java
package sjtu.rfid;
public class HelloBean {
private String HelloWord;
public String getHelloWord() {
return HelloWord;
}
public void setHelloWord(String helloWord) {
HelloWord = helloWord;
}
}