SSM实验作业(二):SPRING 系列教材- 注入对象

一、实验内容

定义一个 Product 对象,并注入一个 Category 对象。

二、实验步骤

步骤 1 : Product.java

Product 类中有对 Category 对象的 setter getter
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;
    }
}

 

步骤 2 : applicationContext.xml

在创建 Product 的时候注入一个 Category 对象
注意,这里要使用 ref 来注入另一个对象

代码

<?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 <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>
 </beans>

 

 

步骤 3 : TestSpring

通过 Spring 拿到的 Product 对象已经被注入了 Category 对象了
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());}}

 

 

步骤 4:实验结果

 

三、实验总结

要在一个对象中注入另外一个类中的对象需要以下三个步骤:
1 、首先需要在类中引入另一个类中的对象:比如在这个实验中要在 Product 对象,并注入一个 Category
对象。拿需要在 Product 的类中引入 Category 对象,并设置 Category setter getter
2 、在 applicationcontext.xml 中,在引入 product bean 时,使用 ref ,将 Category 对象注入: 3 、在 TextSpring 中,定义好 Produc 之后,利用 Category getter 方法来使用 Category
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值