在java開發中有時候我們的一個類需要依賴另外一個類,這種就是依賴關係,創建對象的工作一般由spring容器來完成然後注入給調用者,這種就是依賴注入。
所需要jar文件:http://download.csdn.net/download/six_666666/9959800
文件結構
案例
Boss.java類
public class Boss {
@Resource
public Employee employee; // 依賴
public void _do() {
employee.job();
}
Employee.java類
public class Employee {
public void job() {
System.err.println("do job-->");
}
}
Test.java測試類
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("ioc/spring.xml");
Boss boss = null;
boss = (Boss) ac.getBean("boss2");
boss._do();
}
}
主配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
<bean id="user" class="ioc.User"/>
<context:component-scan base-package="di" />
</beans>
測試結果