Spring管理Bean的三种方式

主要有三种方式:BeanWrapper、BeanFactory和使用ApplicationContext

1、BeanWrapper

package com.example.demo.test;

import java.util.Date;

public class HelloWorld {

	private String msg;

	private Date date;

	public HelloWorld() {
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

}
package com.example.demo.test;

import java.util.Date;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class SpringTest {

	public static void main(String[] args)
			throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Object obj = Class.forName("com.example.demo.test.HelloWorld").newInstance();
		BeanWrapper bw = new BeanWrapperImpl(obj);
		bw.setPropertyValue("msg", "hello world!");
		bw.setPropertyValue("date", new Date());
		System.out.println(bw.getPropertyValue("date") + " " + bw.getPropertyValue("msg"));
	}
}

2、BeanFactory

这个接口有多个实现,最常用的实现是XmlBeanFactory,示例如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE  beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="HelloWorld" class="com.example.demo.test.HelloWorld">
		<property name="msg">
			<value>HelloWorld</value>
		</property>
		<property name="date">
			<ref bean="date"/>
		</property>
	</bean>
	<bean id="date" class="java.util.Date"></bean>
	
</beans>
package com.example.demo.test;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class SpringTest {

	public static void main(String[] args) {
		ClassPathResource res = new ClassPathResource("config/config.xml");
		XmlBeanFactory factory = new XmlBeanFactory(res);
		HelloWorld h = (HelloWorld) factory.getBean("HelloWorld");
		System.out.println(h.getDate() + " " + h.getMsg());
	}
}


3、ApplicationContext

ApplicationContext建立在BeanFactory之上,并增加了其它功能,例如对于国际化的支持、获取资源、事件传递等。示例如下,HelloWorld.java和配置都不用改,测试代码如下

package com.example.demo.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringTest {

	public static void main(String[] args) {
		ApplicationContext ac = new FileSystemXmlApplicationContext("src/config/config.xml");
		HelloWorld h = (HelloWorld) ac.getBean("HelloWorld");
		System.out.println(h.getDate() + " " + h.getMsg());
	}
}
最常用的是ApplicationContext

猜你喜欢

转载自blog.csdn.net/u010142437/article/details/80938526