第一种方法,使用BeanWrapper
示例代码如下:
//通过BeanWrapper来使用bean
HelloWorld helloWorld = new HelloWorld();
BeanWrapper bw = new BeanWrapperImpl(helloWorld);
bw.setPropertyValue("msg","HelloWorld#######");
System.out.println(bw.getPropertyValue("msg"));
输出结果如下:
HelloWorld#######
该方法似乎没用到配置文件......
第二种方法,使用BeanFactory
示例代码如下:
//通过BeanFactory来使用bean
Resource res = new FileSystemResource("config.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
HelloWorld helloWorld = (HelloWorld)factory.getBean("HelloWorld");
System.out.println("HelloWorld.msg: " + helloWorld.getMsg());
第三种,使用ApplicationContext
示例代码如下:
//通过ApplicationContext来获取Spring的配置文件
ApplicationContext actx = new FileSystemXmlApplicationContext(
"config.xml");
//通过Bean的id来获取Bean
HelloWorld helloWorld = (HelloWorld)actx.getBean("HelloWorld");
System.out.println("Hello.msg: " + helloWorld.getDate() + " " + helloWorld.getMsg());