Spring入门_03_构造注入

实体类 Student.java

package com.umgsai.spring.entity;
import java.util.Date;
public class Student {
    private int id;
    private String name;
    private String sex;
    private Date birthday;
    public Student(int id, String name, String sex, Date birthday) {//构造函数
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
    }
//省略其他get、set方法
}

applicationContext.xml

<bean id="student" class="com.umgsai.spring.entity.Student">
    <constructor-arg value="1"/>
    <constructor-arg value="umgsai"/>
    <constructor-arg value="M"/>
    <constructor-arg ref="cur"/><!--引用-->
</bean>
<bean id="cur" class="java.util.Date"/>

测试注入

BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student)factory.getBean("student");
System.out.println(student.getId()+":"+student.getName());


本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1255907

原文地址:https://www.cnblogs.com/umgsai/p/3908115.html