dao层:
package com.wuyonghu.insert;
public interface TestDao {
public void getConn();
}
package com.wuyonghu.insert;
public class TestDaoImpl implements TestDao {
public void getConn() {
System.out.println("获得了数据库的连接");
}
}
service层:
package com.wuyonghu.insert;
public interface TestService {
public void serviceConn();
}
package com.wuyonghu.insert;
public class TestServiceImpl implements TestService {
private TestDao testDaoImpl;
public TestServiceImpl(TestDao testDaoImpl) {
this.testDaoImpl = testDaoImpl;
}
/*
* 使用setter注入方式 public void setTestDaoImpl(TestDao testDaoImpl) {
* this.testDaoImpl = testDaoImpl; }
*/
public void serviceConn() {
testDaoImpl.getConn();
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean id="testServiceImpl" class="com.wuyonghu.insert.TestServiceImpl">
<!-- <property name="testDaoImpl" ref="testDaoImpl"></property> -->
<constructor-arg name="testDaoImpl" ref="testDaoImpl"></constructor-arg>
</bean>
<bean id="testDaoImpl" class="com.wuyonghu.insert.TestDaoImpl"></bean>
</beans>
测试代码:
@Test
public void testHello3() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
TestServiceImpl bean = (TestServiceImpl) context.getBean("testServiceImpl");
bean.serviceConn();
}