[spring] spring学习笔记(1): 通过xml实现依赖注入

依赖注入是spring框架中一个重要思想 - Inversion of Control(IoC) - 的实现, 大体上来说, 就是通过配置Bean对象, 让spring内置的方法来为主对象创建需要的依赖对象; 打个比方, 在java中, 当我们想要使用某个类时, 应当通过new关键字来指定, i.e.

// 在这里创建一个类, 他需要使用另一个类的方法
public class Player {
    public void attack(){
        //创建一把剑, 使用new
        Weapon sword = new Weapon();
        //调用方法得到攻击力
        num_attack = sword.getAttack();
        System.out.println("Player@kapiBara deals " + num_attack + " damage!");
    }
}

可以看到我们使用new方法创建了一个weapon对象, 并把它给Player对象使用
然而通过spring, 我们可以通过3种方法和xml实现依赖注入, 所以接下来要修改这个类⬆️

用来测试的主函数

在此之前, 先来写一个测试用函数testAttack, 因为主函数的结构差不多; 利用xml注入依赖需要ApplicationContext的帮忙

// Test.java
public class Test {
    public static void main(String[] args) {
        //1.初始化Spring容器,按路径加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //2.通过容器获取实例对象,getBean()方法中的参数是bean标签中的id, 传入两个参数是一种保险的使用方式
        Player p1 = (Player) applicationContext.getBean("player", Player.class);
        //3.调用实例中的方法
        p1.attack();
    }
}

setter(常用): 使用<property>, name和ref

xml文件怎么写?(只有bean定义部分)

<!-- bean definitions here -->
<!--将指定类都配置给Spring,让Spring创建其对象的实例,一个bean对应一个对象-->
<bean id="weapon" class="com.demo.Weapon"></bean>

<bean id="player" class="com.demo.player">
	<!--通过setter注入-->
	<property name="lv" value="60"></property>
	<property name="weapon" ref="weapon"></property>
</bean>

对应的Player类

public class Player {
	private int lv;
    //引入参数
    private Weapon w;
    //创建setter方法
    public void setWeapon(Weapon w) {
        this.w = w;
    }

    public void attack(){
        //调用方法
        num_attack = w.getAttack();
        System.out.println("Player@kapiBara deals " + num_attack + " damage!");
    }
}

构造器(常用)

xml文件怎么写?(只有bean定义部分)

<!-- bean definitions here -->
<!--将指定类都配置给Spring,让Spring创建其对象的实例,一个bean对应一个对象-->
<bean id="weapon" class="com.demo.weapon"></bean>

<bean id="player" class="com.demo.Player">
	<!--通过构造函数注入,ref属性表示注入另一个对象-->
	<constructor-arg ref="weapon"></constructor-arg>
</bean>

对应的Player类

public class Player {
    //引入参数
    private Weapon w;
    //创建有参构造函数
    public Player(Weapon w) {
        this.w = w;
    }

    public void attack(){
        //调用方法
        num_attack = w.getAttack();
        System.out.println("Player@kapiBara deals " + num_attack + " damage!");
    }
}

接口注入(不常用)

结论

运行之后结果都是一样的, 但是我们的重点来到了xml配置文件上, 而不用在主体类(Player)里用new来创建引用对象了; 如果Weapon类发生了变化, 那么只要修改xml文件的配置就行了

posted @ 2024-01-16 11:47  Akira300000  阅读(10)  评论(0编辑  收藏  举报