Spring框架中<bean>第一种补充(1)

通过依赖注入的方法:

  Course类中使用teacher类:

package org_shitang_entity;

public class Course {
    private String courseName;
    private int courseHour;
    private teacher teacher1;
    
    public String getCourseName() {
        return courseName;
    }
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
    public int getCourseHour() {
        return courseHour;
    }
    public void setCourseHour(int courseHour) {
        this.courseHour = courseHour;
    }
    public teacher getTeacher1() {
        return teacher1;
    }
    public void setTeacher1(teacher teacher1) {
        this.teacher1 = teacher1;
    }
    public void showInfo(){
        System.out.println(this.courseName+","+this.teacher1.getName()+","+this.courseHour);
    }
}

teacher类中:

package org_shitang_entity;

public class teacher {
    private String name;
    private int age;
    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;
    }
}

在bean中加入其中teacher中的复制使用ref

<bean id="Course" class="org_shitang_entity.Course">
    <property name="courseName" value="java"></property>
    <property name="courseHour" value="1"></property>
    <property name="teacher1" ref="teacher"></property>
</bean>
<bean id="teacher" class="org_shitang_entity.teacher">
    <property name="name" value="ls"></property>
    <property name="age" value="19"></property>
</bean>

main函数中:

ApplicationContext conext=new ClassPathXmlApplicationContext("applicationContext.xml");
        Course course=(Course)conext.getBean("Course");
        course.showInfo();

猜你喜欢

转载自www.cnblogs.com/lmff/p/12751875.html