Spring管理Bean的三种方式

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)、博主微信(guyun297890152)、QQ技术交流群(183198395)。

主要有三种方式: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,示例如下





	
		
			HelloWorld
		
		
			
		
	
	
	
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

你可能感兴趣的:(Spring)