码迷,mamicode.com
首页 > 编程语言 > 详细

Spring 依赖注入(一、注入方式)

时间:2017-04-01 16:24:01      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:cat   []   context   value   运行时   加载   print   sys   name   

注入方式主要有:属性注入、构造注入等

 

下面看一个实例:

1.新建一个接口IPet

package entities;

public interface IPet {
    public String getName();
    public void setName(String name);
    public void sleep();
}

2.新建两个类Dog和Cat

package entities;

public class Cat implements IPet{
    
    //程序运行时,Cat的属性会被xml文件的属性注入代替
    private String name = "kitty";
    private int age = 2;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public void sleep() {
        System.out.println(name + "小猫睡了");        
    }    
}
package entities;

public class Dog implements IPet{
    public String name;
    public int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    //构造方法重载
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void sleep() {
        System.out.println(name + "小狗睡了");
    }
}

3.配置beans.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">
    
    <!--指向Cat类,调用时直接用id的值-->
   <bean id="pet1" class="entities.Cat">
        <!--属性注入-->
        <property name="name" value="tom"></property>
        <property name="age" value="3"></property>
    </bean>

  <bean id="pet2" class="entities.Dog">
        <!-- 构造方法注入 -->
        <constructor-arg name="name" value="An"></constructor-arg>
        <constructor-arg name="age" value="4"></constructor-arg>
    </bean>
   
</beans>

4.读取配置文件并运行

package entities;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        //加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");    

     //读取xml文件中Cat和Dog对应的id IPet pet1 = (IPet)context.getBean("pet1"); IPet pet2 = (IPet)context.getBean("pet2"); pet1.sleep(); pet2.sleep(); } }

运行结果:

<!--Cat类中的属性被xml文件的属性代替-->
tom小猫睡了
<!--读取xml文件的构造方法注入,通过Dog类中的构造函数给属性赋值--> an小狗睡了

 

Spring 依赖注入(一、注入方式)

标签:cat   []   context   value   运行时   加载   print   sys   name   

原文地址:http://www.cnblogs.com/jonsnow/p/6656399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!