spring-依赖注入的方式

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容器中加入对应类的对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值