spring核心之依赖注入(一)设置注入
2011-10-09 15:50
288 查看
设置注入是指IOC容器使用属性的setter方法来注入被依赖的实例,此方法很直观;
这里有两层结构service和action
service层的实现类personserviceImpl部分代码如下:
其中personserviceImpl调用了personAction的add()方法;
这里就需要我们在spring的配置文件中对它进行配置
applicationContext.xml中我们需要先配置两个实现类的bean实例
然后在personservice中设置属性引用personaction 这里id是bean实例的唯一标志位需要按照spring的官方命名方式命名,class是类对象的位置,ref则是依赖对象spring会自动在配置文件中寻找ref所指的对象。
到此我们的设置注入就算完成了,接下来就要测试是否注入成功,那就在junit测试类中进行测试即可。
这里有两层结构service和action
service层的实现类personserviceImpl部分代码如下:
private PersonAction personAction; /** * @return the personAction */ public PersonAction getPersonAction() { return personAction; } /** * @param personAction the personAction to set */ public void setPersonAction(PersonAction personAction) { this.personAction = personAction; } public void save() { System.out.println("这是service层的实现类save()"); personAction.add(); }
其中personserviceImpl调用了personAction的add()方法;
这里就需要我们在spring的配置文件中对它进行配置
applicationContext.xml中我们需要先配置两个实现类的bean实例
<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.0.xsd"> <bean id="personAction" class="com.ncut.action.PersonActionImpl"></bean> <bean id="personService" class="com.ncut.service.PersonServiceImpl"> <property name="personAction" ref="personAction"></property> </bean> </beans>
然后在personservice中设置属性引用personaction 这里id是bean实例的唯一标志位需要按照spring的官方命名方式命名,class是类对象的位置,ref则是依赖对象spring会自动在配置文件中寻找ref所指的对象。
到此我们的设置注入就算完成了,接下来就要测试是否注入成功,那就在junit测试类中进行测试即可。
public class springTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void instanceSpring() { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); PersonService personService=(PersonService)ctx.getBean("personService"); personService.save(); } }
相关文章推荐
- spring核心之依赖注入(一)设置注入
- spring核心之依赖注入(一)设置注入
- Spring读书笔记-----Spring核心机制:依赖注入 .
- spring--核心技术--依赖注入
- Spring的核心机制:依赖注入
- Spring的核心机制依赖注入简介
- Spring应用、原理以及粗读源码系列(一)--框架总述、以Bean为核心的机制(IoC容器初始化以及依赖注入)
- Spring的核心机制依赖注入简介
- Spring核心机制:依赖注入
- spring使用aop时需要设置proxy-target-class="true" 否则无法依赖注入
- Spring核心学习(5)将Bean注入Bean-解析依赖
- Spring读书笔记-----Spring核心机制:依赖注入
- Spring的核心机制依赖注入简介
- spring使用aop时需要设置proxy-target-class="true" 否则无法依赖注入
- 什么是依赖注入--Spring的核心机制依赖注入简介
- Spring 的核心机制:依赖注入
- Spring进阶之路(1)-Spring核心机制:依赖注入/控制反转
- Spring3核心技术之DI依赖注入
- Spring的学习(三):核心机制:依赖注入
- spring使用aop时需要设置proxy-target-class="true" 否则无法依赖注入