spring之在配置Bean时如何关联不同的Bean

Car.java

package com.gong.spring.beans;

public class Car {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Car [name=" + name + "]";
    }
    
}

Student.java

package com.gong.spring.beans;

public class Student {
    private String name;
    private int age;
    private double score;
    private Car car;
    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;
    }
    public double getScore() {
        return score;
    }
    public void setScore(double score) {
        this.score = score;
    }
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", score=" + score + ", car=" + car + "]";
    }
    
    
}

applicationContext.xml



    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">
    
    car" class="com.gong.spring.beans.Car">
        
    
    
    class="com.gong.spring.beans.Student">
        
        
                    
        ref="car">
    
    

Main.java

package com.gong.spring.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        //1.创建spring的IOC容器对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.从容器中获取Bean实例
        Student student = (Student) ctx.getBean("student"); 
        System.out.println(student.toString());
    }
}

输出:

当然,也可以这么写:

         
            
        

我们也可以在bean的内部配置相应的Bean,这个Bean就是一个内部bean,不能被外部使用。

        
            class="com.gong.spring.beans.Car">
                
                    baoma
                
            
        

你可能感兴趣的:(spring之在配置Bean时如何关联不同的Bean)