Spring 依赖注入

来源:互联网 发布:php数组最大长度限制 编辑:程序博客网 时间:2024/06/08 00:32

Spring 注入 是指在启动Spring 容器加载bean配置的时候,完成对变量的复制行为 ,有两种注入方式

setter方法 设值注入
实体类

public class ImplOne implements Api {    // setter注入    private Api two = null;// 声明需要的资源   // 写setter方法,开辟一个 从外部传入所需要资源的窗口,这个外部就是配置文件    public void setTwo(Api api) {        this.two = api;    }    private String str = "";    public void setStr(String str) {        this.str = str;    }    @Override    public String t(int a) {        // TODO Auto-generated method stub        two.t(a - 2);        System.out.println("now in Impl One t,a==" + a + "  str=" + str);        return "hello==" + a;    }}

配置文件

 <!-- ImplOne中的属性(字段),对应这里的一个<property>     ImplOne类中有属性(字段)two,所以定义property 的name 为two property的ref(参考)定义这个属性 实例化对应的类     ImplOne雷中有属性str,所以定义property的那么为str, value值为smx -->    <bean name="dep-test" class="cn.javass.spring3.hello.ImplOne">        <property name="two" ref="dep-two"></property>        <property name="str"><value>smx</value></property>    </bean>    <bean name="dep-two" class="cn.javass.spring3.hello.ImplTwo"></bean>

构造器注入
Java 实体类ImplOne中

    private int age = 0;    private int age1 = 0;    private String name = "";    public ImplOne(int age, int age1, String name) { // 构造器注入        // TODO Auto-generated constructor stub        this.age = age;        this.age1 = age1;        this.name = name;        System.out.println("agagagagg==" + age + " , age1=" + age1 + " , name=" + name);    }

配置文件

<bean name="dep-test" class="cn.javass.spring3.hello.ImplOne">        <!--  构造器注入  按照参数的名称匹配-->        <constructor-arg name="age"><value>15</value></constructor-arg>        <constructor-arg name="age1"><value>5</value></constructor-arg>        <constructor-arg name="name"><value>smxhahaha</value></constructor-arg>        <!-- setter注入 -->        <property name="two" ref="dep-two"></property>        <property name="str"><value>smx</value></property></bean><bean name="dep-two" class="cn.javass.spring3.hello.ImplTwo"></bean>
原创粉丝点击