[b]依赖注入:[/b]
1. 构造器注入
配置文件(放classpath根目录下)
接口
imp实现类
junit测试
2.静态工厂方法方式
静态工厂方法(有statice关键字)
bean配置
3.工厂方法方式
工厂方法
bean配置
1. 构造器注入
配置文件(放classpath根目录下)
<?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="org.spring.imp.PersonServiceImp"/>-->
接口
package org.spring.service;
public interface PersonService {
public void savePerson();
}
imp实现类
package org.spring.imp;
import org.spring.service.PersonService;
public class PersonServiceImp implements PersonService {
public void savePerson() {
System.out.println("执行了PersonSerciceImp.savePerson()方法...");
}
}
junit测试
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test public void InitSpringContext(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
// 默认构造方法注入
PersonService personService = (PersonServiceImp)ctx.getBean("personService");
personService.savePerson();
}
}
2.静态工厂方法方式
静态工厂方法(有statice关键字)
package org.spring.unit;
public class PersonServiceFactory {
public static PersonService createPersonService(){
return new PersonServiceImp();
}
}
bean配置
<bean id="personServiceFactory" class="org.spring.unit.PersonServiceFactory" factory-method="createPersonService"/>
3.工厂方法方式
工厂方法
public PersonService createPersonService2(){
return new PersonServiceImp();
}
bean配置
<bean id="personServiceFactory" class="org.spring.unit.PersonServiceFactory"/>
<bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonService2"/>