1. 程式人生 > >java框架之spring(二)

java框架之spring(二)

注入物件(本例是接著上一個繼續進行)

在上例中,對Category的name屬性注入了"花季歲月"字串 
在本例中 ,對Product物件,注入一個Category物件

1、首先新建一個類Product.java

package com.hjsy.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="hjsy" class="com.hjsy.pojo.Category">
        <property name="name" value="花季歲月" />
    </bean>
    <bean name="hjsy1" class="com.hjsy.pojo.Product">
        <property name="name" value="花季歲月1" />
        <property name="category" ref="hjsy" />
    </bean>
</beans>
3、測試

package spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hjsy.pojo.Product;
public class TestSpring {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
        Product product = (Product) context.getBean("hjsy1");
        System.out.println(product.getName());
        System.out.println(product.getCategory().getName());
	}
}
4、執行輸出結果



原始碼:連結:https://pan.baidu.com/s/1c3GcNXe 密碼:k8vz