Spring 依赖注入(1)访问器注入

例子:
Spring中:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.3.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
		<bean id="dao1" class="com.nueedu.demo4.dao.impl.TestDAOImpl1"></bean>
		<bean id="dao2" class="com.nueedu.demo4.dao.impl.TestDAOImpl2"></bean>
		<bean id="service" class="com.neuedu.demo4.service.TestService">
			<property name="dao" ref="dao2"></property>
		</bean>

</beans>

testdao中:

package com.nueedu.demo4.dao;

public interface TestDAO {
	public void Haha();
}

TestDAOImpl1:

package com.nueedu.demo4.dao.impl;

import com.nueedu.demo4.dao.TestDAO;

public class TestDAOImpl1  implements TestDAO{

	@Override
	public void Haha() {
		// TODO 自动生成的方法存根
		System.out.println("dao1的方法在执行");
	}

}

TestDAOImpl2中:

package com.nueedu.demo4.dao.impl;

import com.nueedu.demo4.dao.TestDAO;

public class TestDAOImpl2  implements TestDAO{

	@Override
	public void Haha() {
		// TODO 自动生成的方法存根
		System.out.println("dao2的方法在执行");
	}

}

TestService 中:
这里一般都写上set和get方法

package com.neuedu.demo4.service;

import com.nueedu.demo4.dao.TestDAO;

public class TestService {
	
	private TestDAO dao;
	
	public TestDAO getDao() {
		return dao;
	}

	public void setDao(TestDAO dao) {
		this.dao = dao;
	}

	public void test(){
		dao.Haha();
	}
}

最后的测试类:

package com.neuedu.demo4.service;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
		
		ClassPathXmlApplicationContext cp = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		TestService ts = (TestService) cp.getBean("service");
		ts.test();

	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值