Spring学习笔记(二):注入对象

学习资料来源:http://how2j.cn/k/spring/spring-injection/88.html

在本例中 ,对Product对象,注入一个Category对象
创建了一个新的Product(产品)类,这个类中除本身id、name属性的getter和setter外,还有Category这个类的setter和getter方法即getCategory()和setCategory()

package com.how2java.pojo;
 
public class Product {
 
    private int id;
    private String name;
    private Category category;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }
}

在xml中以"p"关键字添加Product的bean,其中name属性赋值为product1,以"c"关键字为Product注入一个Category对象

    <bean name="c" class="com.how2java.pojo.Category">
        <property name="name" value="category 1" />
    </bean>
    <bean name="p" class="com.how2java.pojo.Product">
        <property name="name" value="product1" />
        <property name="category" ref="c" />
    </bean>

这样,在测试用例TestSpring中,通过getBean("p")产生的Product对象也已经包含了Category对象,并且可以调用其中的getName()方法了

package com.how2java.test;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.how2java.pojo.Product;
 
public class TestSpring {
 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
 
        Product p = (Product) context.getBean("p");
 
        System.out.println(p.getName());
        System.out.println(p.getCategory().getName());
    }
}

猜你喜欢

转载自blog.csdn.net/HiflyMaple/article/details/87004479