首页 > 学院 > 开发设计 > 正文

spring----filed值注入

2019-11-08 03:23:53
字体:
来源:转载
供稿:网友

1.什么是filed值

filed值指的是,在static环境下的变量,该变量属于类,则叫做类filed值

                        或者非static环境下的变量,对象filed值

2.filed注入的作用.

将一个静态或者非静态的filed值赋值给实现类.(注意:filed注值和普通注值不能同时使用否则报错)

3.filed注值步骤:(接下来我们采用静态filed注值法)

3.1实现类

package test;public class Son {    public  int age;    public String name;    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;    }    }

3.2.设定静态filed值(关键一步)

package test;public class filed {    public static final String TEST_FIELD="林泽森";}

3.3

配置文件

<bean id="son" class="test.Son">        <PRoperty name="name">            <bean id="test.filed.TEST_FIELD" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/><!--关键类,没有它,filed注入不能成功-->        </property>    </bean>

3.3.1(对于3.3的配置的补充)该配置中的<bean id="test.filed.TEST_FIELD">仅对于静态值域来说可以 类名.变量   而对于对象值域来说  这应该这样配置

       <bean id="filedadd" class=" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">

                        <property name="targetClass"  value="test.filed(值域所在的类)">

                        <property name="targetFiled"  value="TEST_FIELD(值域变量名)">

       </bean>

配置翻译:test.filed.TEST_FIELD的filed值通过FieldRetrievingFactoryBean类赋给test.Son类中的name属性

3.4测试类

public class filedtest {        public static void main(String[] args) {            applicationContext ac=new ClassPathxmlApplicationContext("bean.xml");            Son son=ac.getBean("son",Son.class);            System.out.println("系统获取son3的age属性值:"+son.getName());        }}

3

4.运行结果

5.总结:filed注值方式是替代了普通的注值方式(value=""),因此他们两者是不能同时兼容的.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表