Spring注入属性、对象


对Category和Product注入属性,并且对Product对象,注入一个Category对象

一、新建项目

二、导包

三、新建Category类

package com.yyt.pojo;

public class Category {
    private int id;
    private String name;
    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;
    }
  }

四、新建Product类,将添加一个Category类型属性

package com.yyt.pojo;

public class Product {
     private int id;
       private String name;
       private float price;
       private Category category;

五、在src目录下新建applicationContext.xml文件

要注入对象,需在property中添加ref=“该类在bean中的name”,例如本次的 “c”是Category在bean中的name值

<?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.yyt.pojo.Category"> <property name="id" value="1" /> <property name="name" value="category 1" /> </bean> <bean name="p" class="com.yyt.pojo.Product"> <property name="id" value="1" /> <property name="name" value="product 1" /> <property name="price" value="8848" /> <property name="category" ref="c" /> </bean> </beans>

六、Test类

package com.yyt.test;

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

import com.yyt.pojo.Category;
import com.yyt.pojo.Product;

public class Test {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] {"applicationContext.xml"});
        Category cg = (Category) context.getBean("c");
        System.out.println("id:"+cg.getId()+" name:"+cg.getName());
        
        
        Product p = (Product) context.getBean("p");
        System.out.println("id:"+p.getId()+" name:"+p.getName()+" price:"+p.getPrice());
        //输出注入的对象
        System.out.println(p.getCategory().getName());

    }

}

注:基于框架的程序要成功运行,对于JAR包的版本,配置文件的正确性有着苛刻的要求,任何一个地方出错了,都会导致框架程序运行失败。

该项目上传了GitHub:https://github.com/yeyangtao/Spring

posted @ 2019-05-12 18:42  奥兔man  阅读(1282)  评论(0编辑  收藏  举报