1.静态工厂注入和set方法注入差不多
第一步:先创建一个静态工厂
/**
* 定义静态工厂类
*/
public class StaticFactory {
public static TypeDao createTypeDao(){
return new TypeDao();
}
}
第二步:准备两个javaBean对象
public class TypeDao {
public void test(){
System.out.println("TypeDao.test");
}
}
public class TypeService {
TypeDao typeDao;
public void setTypeDao(TypeDao typeDao) {
this.typeDao = typeDao;
}
public void test(){
System.out.println("TypeService.test");
typeDao.test();
}
}
第三步:写xml文件
<bean id="typeService" class="com.zks.service.TypeService">
<property name="typeDao" ref="typeDao"/>
</bean>
<bean id="typeDao" class="com.zks.factory.StaticFactory" factory-method="createTypeDao"/>
第四步:测试
public class test2 {
public static void main(String[] args) {
//获取上下文环境
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring2.xml");
TypeService typeService= (TypeService) applicationContext.getBean("typeService");
typeService.test();
}
}
实例化方法注入只要把配置文件改一下就行,如图所示:
这两种方法本质上也是set方法注入,工作中用的很少,主要还是set方法注入和构造器注入。