您的位置:首页 > 编程语言 > Java开发

spring核心之依赖注入(一)设置注入

2011-10-09 15:50 253 查看
设置注入是指IOC容器使用属性的setter方法来注入被依赖的实例,此方法很直观;

这里有两层结构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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: