Bean的属性注入

一般来说javaBean对象的属性大多设为私有的,同时也配有相应的get和set方法。那么spring就可以借助其set方法,为其属性注入相应的值

新建一个班级类:

public class Class {
    private String name = "testClass";

    public String getName() {
        return name;
    }
}
新建一个学生类:

public class Student {
    private String name;
    private Class stuClass;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Class getStuClass() {
        return stuClass;
    }

    public void setStuClass(Class stuClass) {
        this.stuClass = stuClass;
    }
}
在spring的配置文档当中可以利用<property>元素配置bean的属性。

①如果为bean注入简单的值,比如说字符串,数字等,可以直接为<property>设置value属性。

②如果为bean注入对象,引用其他bean。那么可以为<property>设置ref属性,其值就是其他bean的id值。(ref注入,也可以改为<property>的内部bean)

③spring还提供了命名空间p来替代<property>为bean注入属性。想使用命名空间p,需要在配置中增加xmlns:p="http://www.springframework.org/schema/p"

具体的配置例子如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="tClass" class="com.test.beanSet.Class"/>

    <!-- property注入属性,如果是引用对象,那么可以利用ref来注入 -->
    <bean id="tStudent" class="com.test.beanSet.Student">
        <property name="name" value="Xiao Ming"/>
        <property name="stuClass" ref="tClass"/>
    </bean>

    <!-- 除了ref注入对象,还可以直接在property中配置内部bean -->
    <bean id="tStudent2" class="com.test.beanSet.Student">
        <property name="name" value="Xiao Hong"/>
        <property name="stuClass">
            <bean class="com.test.beanSet.Class"/>
        </property>
    </bean>

    <!-- 另外可以使用命名空间p来替代property -->
    <bean id="tStudent3" class="com.test.beanSet.Student" p:name="Xiao Li" p:stuClass-ref="tClass"/>


</beans>
测试代码:

public class BeanSetApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("testBeanSet.xml");
        Student tStudent = (Student) context.getBean("tStudent");
        System.out.println(tStudent.getName());
        System.out.println(tStudent.getStuClass().getName());


        Student tStudent2 = (Student) context.getBean("tStudent2");
        System.out.println(tStudent2.getName());
        System.out.println(tStudent2.getStuClass().getName());

        Student student3 = (Student) context.getBean("tStudent3");
        System.out.println(student3.getName());
        System.out.println(student3.getStuClass().getName());

    }
}
运行结果:

Xiao Ming
testClass
Xiao Hong
testClass
Xiao Li
testClass





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值