Java自学之spring:注入对象

学习目的:

spring初识中,对Category的name属性注入了"category 1"字符串。

在小节学习中 ,对Product对象,注入一个Category对象。

Part 1

新建一个pojo:Product,且Category为其中一个属性

package cn.vaefun.pojo;

public class Product {
	private String name;
	private Category category;
	
	
	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public String getName() {
		return name;
	}

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

Part 2

配置xml:为Product新增一个bean,并为属性category注入(ref)bean c,完成注入对象。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="Index of /schema/aop"
    xmlns:tx="Index of /schema/tx"
    xmlns:context="Index of /schema/context"
    xsi:schemaLocation="
   Index of /schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   Index of /schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   Index of /schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   Index of /schema/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
    <bean name="c" class="cn.vaefun.pojo.Category">
        <property name="name" value="category 1" />
    </bean>
    
    <bean name="p" class="cn.vaefun.pojo.Product">
        <property name="name" value="product 1" />
        <property name="category" ref="c" />
    </bean>
  
</beans>

Part 3

通过spring获取到Product对象,同时获取到注入的对象Category。

package cn.vaefun.test;

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

import cn.vaefun.pojo.Product;

public class TestSpring {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
		Product product = (Product)context.getBean("p");
		System.out.println(product.getName());
		System.out.println(product.getCategory().getName());
	}
}

Part 4

成功获取到Product对象以及注入的Category对象,并输出其name。

v2-7c0b1dbe3c101263ef01350aec5cf23b_b.jpg

posted @ 2020-02-14 18:46  IMKKA  阅读(1)  评论(0)    收藏  举报  来源