依赖注入_注解版_注入对象

第一步:准备两个实体

//需要注入product的实体car

@Component("car")
public class Car {
    @Value("#{'一汽大众'}")
    private String name;
    @Value("#{10000}")
    private Double price;

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

//product实体

@Component("product")
public class Product {
    //注入对象
    @Value("#{car}")
    private Car car;
    //必须有setter方法
    public void setCar(Car car){
        this.car=car;
    }
    public Car getCar(){
        return car;
    }

}

第二步:配置(自动扫描包)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="it.heima.domain"/>
</beans>

第三步:测试

@Test
public void test1(){
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext_annotation.xml");
    Product product = applicationContext.getBean("product", Product.class);
    System.out.println(product.getCar());
}

结果:

说明注入成功

猜你喜欢

转载自blog.csdn.net/weixin_42333583/article/details/81535527
今日推荐