项目结构如下所示:
1、实现接口PersonServiceBean.java:
/*
*@Author swxctx
*@time 2016年9月26日
*/
package com.sw.servicebean;
import com.sw.service.PersonService;
public class PersonServiceBean implements PersonService {
/* (non-Javadoc)
* @see com.sw.servicebean.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、建立文件进行注入,并且使用set方法对PersonServiceBean的方法进行注入
UserBean.java;
/*
*@Author swxctx
*@time 2016年9月26日
*/
package com.sw.servicebean;
import com.sw.service.PersonService;
public class UserBean{
private PersonService personService;
public void setPersonService(PersonService personService) {
this.personService = personService;
}
public void save(){
personService.save();
}
}
4、建立spring配置文件
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">
<!-- 使用set方法进行依赖注入 -->
<bean id="personServiceBean" class="com.sw.servicebean.PersonServiceBean"></bean>
<bean id="userBean" class="com.sw.servicebean.UserBean">
<property name="personService" ref="personServiceBean"></property>
</bean>
</beans>
5、新建junit测试类;
Test.java:
/*
*@Author swxctx
*@time 2016年9月26日
*/
package com.sw.test;
import org.junit.BeforeClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sw.servicebean.UserBean;
public class Test {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@org.junit.Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserBean userBean = (UserBean)ctx.getBean("userBean");
userBean.save();
}
}
执行结果如下: