spring-依赖注入
一个应用中,完成任务大多都是多个类协作来完成的。
按照传统的做法,每个对象负责管理与自己相互协作的对象
(即它所依赖的对象)的引用,这将会导致高度耦合和难以测试的代码。
依赖注入,就是不需要这个对象去考虑它所依赖的类如何生成,有其他的方式负责把这个类依赖的对象,注入进来
1.每个类自己负责自己需要的对象
class Soldier{
private Weapon weapon;
public Soldier(){
this.weapon=new weapon();
}
public void attact(){
weapon.attact();
}
}
Soldier采用在构造器中直接构建Weapon接口的对象的方式,导致这俩个类过于耦合,不利于修改。
2.采用构造器注入
class Soldier{
private Weapon weapon;
public Soldier(Weapon weapon){
this.weapon=weapon;
}
public void attact(){
weapon.attact();
}
}
interface Weapon{
public void attact();
}
public class Gun implements Weapon{
public void attact() {
System.out.println("use a gun to attact...");
}
}
在Soldier时可以传入各种的Weapon,耦合度大大降低。这就是采用构造器注入依赖。
示例
public Soldier Test{
public static void mian(String [] args){
Weapon weapon =new Gun();
Soldier soldier =new Soldier (weapon);
soldier.attact();
}
}
use a gun to attact...
为soldier注入了一个Gun对象,这就不需要由soldier考虑如何生成Weapon 对象。并且可以传入Gun,Sword等各种Weapon。
3.Spring提供的XML配置方式
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="gun" class="Gun">
</bean>
<bean id="soldier" class="Soldier">
<property name="weapon" ref="gun"></property>
</bean>
</beans>
public class MainTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Soldier soldier=(Soldier) ctx.getBean("soldier");
soldier.attact();
}
}
use a gun to attact...
使用Spring的XML配置方式,我们甚至都不需要在使用的时候提供对应的类型了,只需要在XML文件中定义好,修改起来也特别方便。
4.Spring提供的基于Java的配置方式
@Configuration
public class SoldierConfig {
@Bean
public Soldier getSoldier(){
Soldier soldier=new Soldier(getGun());
return soldier;
}
@Bean
public Weapon getGun(){
Weapon gun=new Gun();
return gun;
}
}
public class MainTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Soldier soldier=(Soldier) ctx.getBean(Soldier.class);
soldier.attact();
}
}
通过配置类和 @Bean注解向IOC容器中加入对应类的对象