(静态工厂方法来获取spring bean类)

来源:互联网 发布:g41g42数控车编程方法 编辑:程序博客网 时间:2024/05/29 19:49

在/cn下有一个文件(但是这个可以从其他方法中抽取出来)PersonService.java

package cn;public interface PersonService {public abstract void save();}

在/cn/imp文件夹下有两个java文件PersonServiceBean.java

package cn.imp;import cn.PersonService;public class PersonServiceBean implements PersonService {/* (non-Javadoc) * @see cn.imp.PersonService#save() */public void save(){System.out.println("我是save方法");}}

PersonServiceBeanFactory.java

package cn.imp;public class PersonServiceBeanFactory {public static PersonServiceBean createPersonServiceBean(){return new PersonServiceBean();}}


建立一个测试用test

在junit.test下面SpringTest.java

package junit.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.imp.PersonServiceBean;public class SpringTest {@Test public void instanceSpring(){ApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"beans.xml"});PersonServiceBean personServiceBean=(PersonServiceBean) ctx.getBean("personService");personServiceBean.save();}}

在src文件夹下面有个配置文件

beans.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="personService" class="cn.imp.PersonServiceBeanFactory" factory-method="createPersonServiceBean">    </bean></beans>



原创粉丝点击