【Spring】依赖注入之bean注入

package org.example;

public class Car {
    private String car_name;

    public String getCar_name() {
        return car_name;
    }
    public void setCar_name(String car_name) {
        this.car_name = car_name;
    }

    @Override
    public String toString() {
        return "Car{" +
                "car_name='" + car_name + '\'' +
                '}';
    }
}
package org.example;

public class User {
    private String name;

    private Car car;

    public String getName() {
        return name;
    }

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

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

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


}

 




    
        
    

    
        
        
    

ref表示引用型,ref="car"  表示引用了id为car的bean

name="car"是因为

【Spring】依赖注入之bean注入_第1张图片 

【Spring】依赖注入之bean注入_第2张图片 

package org.example;

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

public class Test {
    public static void main(String[] args) {
     ApplicationContext context  = new ClassPathXmlApplicationContext("beans.xml");
     User user=(User) context.getBean("user");
        System.out.println(user.getName()+"在开"+user.getCar().getCar_name());
    }
}

 【Spring】依赖注入之bean注入_第3张图片

你可能感兴趣的:(Spring,spring,java,前端)