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

设置注入是指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(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值