依赖注入(DI)和控制反转(IoC),意思是一样的
传统方式中,如果JAVA实例A需要另一个实例B,那么需要new B(),然后给A用,也就是有调用者A创建被调用者B的实例
依赖注入模式下:创建被调用者B的工作不再由A完成,而是由Spring容器完成(或者说工厂模式的工厂完成),然后注入调用者,因此也成为依赖注入,因为A和B是依赖关系。
依赖注入有两种方式:
(1)设值注入
Spring通过Set方法为类A的成员注入值。
(2)构造注入
通过构造器注入。
例子如下:
代码逻辑:
Service通过构造器注入dog和cat,也就是构造注入,而dog和cat的属性-年龄是通过set方法注入,也就是设值注入,实现的配置文件如下:
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- <bean id="dog" class="com.ehr.service.Service"></bean> Dog dog =new Dog(); --> <bean id = "dog" class="com.learn.DAO.impl.Dog"> <property name="dage" value="12"></property> </bean> <bean id="cat" class="com.learn.DAO.impl.Cat"> <property name="cage" value="21"></property> </bean> <bean id = "service" class="com.ehr.service.Service"> <constructor-arg ref="dog"></constructor-arg> <constructor-arg ref="cat"></constructor-arg> </bean> </beans>
Service:
</pre>package com.ehr.service;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.learn.DAO.ICat;import com.learn.DAO.IDog;import com.learn.DAO.impl.Cat;import com.learn.DAO.impl.Dog;public class Service {<span style="white-space:pre"> </span>IDog dog;<span style="white-space:pre"> </span>ICat cat;<span style="white-space:pre"> </span><span style="white-space:pre"> </span>public Service(IDog dog, ICat cat){<span style="white-space:pre"> </span>this.dog = dog;<span style="white-space:pre"> </span>this.cat = cat;<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span><span style="white-space:pre"> </span>public static void main(String[] args) {<span style="white-space:pre"> </span>ApplicationContext context = new ClassPathXmlApplicationContext(<span style="white-space:pre"> </span> "applicationContext.xml");<span style="white-space:pre"> </span>Service s1 = (Service) context.getBean("service");<span style="white-space:pre"> </span>s1.dog.bark();<span style="white-space:pre"> </span>s1.cat.bark();<span style="white-space:pre"> </span>}}</p><p>Dog</p><p><pre name="code" class="java">package com.learn.DAO.impl; public class Dog implements com.learn.DAO.IDog { int dage; public void setDage(int dage) { this.dage = dage; } public void bark() { System.out.println("Dog.bark()" + " WangWang " + dage) ; } }
IDog
package com.learn.DAO; public interface IDog { public void bark(); }
Cat
package com.learn.DAO.impl; import com.learn.DAO.ICat; public class Cat implements ICat { int cage; public void setCage(int cage) { this.cage = cage; } @Override public void bark() { System.out.println("Cat.bark()" + cage); } }
ICat
package com.learn.DAO; public interface ICat { public void bark(); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-23 01:41:52