Spring基础实例(依赖注入和控制反转)

前提条件:在http://www.springsource.org/download网站上下载Spring框架,并将spring.jar、log4j-1.2.15.jar、commons-logging.jar加载至工程
1.武器接口

package com.bijian.spring.base3;

public interface Weapon {

   
    void killEnemy();
}

 

2.武器实现类枪

package com.bijian.spring.base3;

public class HandGun implements Weapon {

   
    public void killEnemy() {
        System.out.println("枪杀敌");
    }
}

 

3.士兵类

package com.bijian.spring.base3;

public class Soldier {

    private Weapon weapon;
   
    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }

   
    public void fight() {
        weapon.killEnemy();
    }
}

 

4.applicationContext3.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
  "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="s1" class="com.bijian.spring.base3.Soldier">
        <property name="weapon">
            <ref bean="handgun"></ref>
        </property>
    </bean>
    <bean id="handgun" class="com.bijian.spring.base3.HandGun"></bean>
</beans>

 

5.测试类

package com.bijian.spring.base3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext3.xml");
        Soldier s1 = (Soldier)context.getBean("s1");
        s1.fight();
    }
}

 

        运行结果:枪杀敌

       

        这里使用Spring解决了HandGun和Soldier的耦合问题。Soldier类中再也看不到HandGun的踪影了,Soldier只依赖于接口,而最终Soldier还是使用了HandGun。Sping在这里管理了单个的对象,也管理了对象之间即Soldier和HandGun的依赖关系。原本是由Soldier控制HandGun的实例化的,转变为由Spring容器来控制,这里发生了控制权的转移,这就是控制反转(Inversion of Control,管称IOC)。当Soldier需要HandGun时,Spring会自动将HandGun对象注入给Soldier,这就是依赖注入。

你可能感兴趣的:(spring)