项目结构如下:
、
1、新建PersonServiceBean.java:
/*
*@Author swxctx
*@time 2016年9月26日
*/
package com.sw.serv.impl;
import com.sw.service.PersonService;
public class PersonServiceBean implements PersonService {
/* (non-Javadoc)
* @see com.sw.serv.impl.PersonService#save()
*/
@Override
public void save(){
System.out.println("save-method");
}
}
2、接口PersonService.java:
/*
*@Author swxctx
*@time 2016年9月26日
*/
package com.sw.service;
public interface PersonService {
void save();
}
3、实现静态工厂类PersonServiceFactory.java:
/*
*@Author swxctx
*@time 2016年9月26日
*/
package com.sw.factory;
import com.sw.serv.impl.PersonServiceBean;
public class PersonServiceFactory {
//使用静态方法实例化bean
public static PersonServiceBean createPersonService(){
return new PersonServiceBean();
}
}
4、实现配置文件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 -->
<bean id="personServiceBean" class="com.sw.serv.impl.PersonServiceBean"></bean>
<!-- 使用静态工厂实例化bean -->
<!-- <bean id="personServiceBean" class="com.sw.factory.PersonServiceFactory" factory-bean="createPersonService"></bean> -->
<!-- 使用实例工厂实例化bean -->
<!-- <bean id="personServiceFactory" class="com.sw.factory.PersonServiceFactory"></bean>
<bean id="personServiceBean" factory-bean="personServiceFactory" factory-method="createPersonService"></bean> -->
</beans>
5、测试类PersonTest.java:
/*
*@Author swxctx
*@time 2016年9月26日
*/
package com.sw.test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sw.service.PersonService;
public class PersonTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void test() {
//实例化容器
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
//获取bean
PersonService personService = (PersonService)ctx.getBean("personServiceBean");
//调用业务方法
personService.save();
}
}
执行结果如下: