Spring依赖注入(xml配置)


spring框架最初设计于2003年,作为J2EE开发的轻量级解决方案,目前已经成为构建企业级应用的标准选择和Java开发人员的必备工具。迄今为止Spring 5是最新的主版本。

* Spring特点 *

  • 简化Java开发,代替重量级的Java开发技术。如EJB。
  • 开源
  • 低侵入性

package cn.wind.spring;
//动物类
public interface Animal {
    void say();
}
package cn.wind.spring.impl;

import cn.wind.spring.Animal;

public class Dog implements Animal {

    public Dog() {
        System.out.println("Dog constructor...");
    }

    public void say() {
        System.out.println("wang-wang-wang...");
    }

}
package cn.wind.spring.impl;

import cn.wind.spring.Animal;

public class Cat implements Animal {

    public Cat() {
        System.out.println("Cat constructor...");
    }
    public void say() {
        System.out.println("miao-miao-miao...");
    }

}
package cn.wind.spring.impl;

import cn.wind.spring.Animal;

public class sheep implements Animal {

    public void say() {
        System.out.println("mie-mie-mie...");
    }

}
package cn.wind.spring;

public class Zoo {

    private Animal dog;
    private Animal cat;
    private Animal sheep;

    public Zoo(Animal sheep) {
        this.sheep = sheep;
    }

    public void setSheep(Animal sheep) {
        this.sheep = sheep;
    }

    public void setDog(Animal dog) {
        this.dog = dog;
    }

    public void setCat(Animal cat) {
        this.cat = cat;
    }


    public void speak() {
        dog.say();
        cat.say();
        sheep.say();
    }
}
package cn.wind.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;
//测试类
public class test {

    public static void main(String[] args) {
        //加载Spring上下文(Spring ApplicationContext负责bean对象的创建与组装)
//        ApplicationContext context = new  ClassPathXmlApplicationContext("applicationContext.xml");
        ClassPathXmlApplicationContext context = new  ClassPathXmlApplicationContext("applicationContext.xml");
        //获取bean对象
        Zoo zoo = (Zoo) context.getBean("zoo");
        zoo.speak();
        context.close();
    }
}
#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 name="dog" class="cn.wind.spring.impl.Dog"></bean>
    <bean name="cat" class="cn.wind.spring.impl.Cat"></bean>
    <bean name="sheep" class="cn.wind.spring.impl.sheep"></bean>
    <bean name="zoo" class="cn.wind.spring.Zoo">
      <property name="dog" ref="dog"/>#setter注入
      <property name="cat" ref="cat"/>
      <constructor-arg ref="sheep"/>#构造注入
    </bean>
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值