Spring构造注入——name属性

1 注意事项

        a.使用<contructor-arg标签进行属性赋值;

        b.使用构造注入的类,只需要有参构造方法即可,可以不用无参构造方法,且不用set方法;

2 实验

2.1 Student类(用于构造注入)

package study.domain;


public class Student {
    private int id ;
    private String user;
    private String password;
    private School school;


    public Student(int id, String user, String password, School school) {
        this.id = id;
        this.user = user;
        this.password = password;
        this.school = school;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", user='" + user + '\'' +
                ", password='" + password + '\'' +
                ", school=" + school +
                '}';
    }

}

2.2 School类(作为引用数据类型使用)

package study.domain;

public class School {
    private String name;
    private String location;

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

    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    public String toString() {
        return "School{" +
                "name='" + name + '\'' +
                ", location='" + location + '\'' +
                '}';
    }
}

2.3 配置文件

<?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 id="mySchool" class="study.domain.School">
        <property name="name" value="qhdx"/>
        <property name="location" value="北京"/>
    </bean>
    
    <bean id="myStudent" class="study.domain.Student">
        <constructor-arg name="id" value="007"/>
        <constructor-arg name="password" value="123"/>
        <constructor-arg name="school" ref="mySchool"/>
        <constructor-arg name="user" value="liming"/>
    </bean>
</beans>

2.4 实验结果

package study.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import study.domain.Student;

public class Mytest {
    @Test
    public void test1(){
        String config = "bean.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        Student myStudent = (Student) ctx.getBean("myStudent");
        System.out.println(myStudent);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值