Spring 依賴注入(1)訪問器注入
阿新 • • 發佈:2018-12-15
例子:
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();
}
}