1. 程式人生 > >spring物件屬性及物件關聯

spring物件屬性及物件關聯

Spring 設計的核心是 org.springframework.beans 包,它的設計目標是與 JavaBean 元件一起使用。這個包通常不是由使用者直接使用,而是由伺服器將其用作其他多數功能的底層中介。下一個最高階抽象是 BeanFactory 介面,它是工廠設計模式的實現,允許通過名稱建立和檢索物件。BeanFactory 也可以管理物件之間的關係。

一、物件建立

1.1、建立一個user物件

User.java

package com.testfan.spring.ioc;

import java.util.List;
import java.util.Map;
import
java.util.Set; public class User { private String name; private int age; private Car car; private List<Car> carList; private Set<Car> setlist; private Map<String, Object> map; public Map<String, Object> getMap() { return map; } public
void setMap(Map<String, Object> map) { this.map = map; } public Set<Car> getSetlist() { return setlist; } public void setSetlist(Set<Car> setlist) { this.setlist = setlist; } public List<Car> getCarList() { return carList; } public
void setCarList(List<Car> carList) { this.carList = carList; } public User() { System.out.println(" create "); } public void init() { System.out.println("init---"); } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public static void main(String[] args) { try { Class clz= Class.forName("com.testfan.spring.ioc.User"); User object =(User) clz.newInstance(); } catch (Exception e) { e.printStackTrace(); } } }
1.2 BeanFactory 支援兩個物件模型。
1.2.2 單態

模型提供了具有特定名稱的物件的共享例項,可以在查詢時對其進行檢索。Singleton 是預設的也是最常用的物件模型。對於無狀態服務物件很理想。

xml檔案(ioc.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

     <bean id="user" class="com.testfan.spring.ioc.User">
     </bean>
</beans>

IocTest.java

package com.testfan.spring.ioc;

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

public class IocTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        //byname/id
        User user = (User) context.getBean("user");
        System.out.println(user);
        //bytype
        User user2 = context.getBean(User.class);
        System.out.println(user2);

        System.out.println(user==user2);
    }
}

輸出如下:user=user2
這裡寫圖片描述

1.2.3 原型

模型確保每次檢索都會建立單獨的物件。在每個使用者都需要自己的物件時,原型模型最適合。

xml檔案(ioc.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

     <bean id="user" class="com.testfan.spring.ioc.User"  scope="prototype">
          <property name="name" value="zhangsan"></property>
          <property name="age" value="20"></property>
     </bean>
</beans>

2.2 物件關聯(set、list、map的管理)

ref:引用其他bean物件
property:呼叫set方法
constructor-arg:呼叫構造方法

Car.java(建立一個car物件)

package com.testfan.spring.ioc;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("cartest")
public class Car {
    private String name;
    private double price;

    @Resource(name="user")
    private User user2;


    public User getUser2() {
        return user2;
    }

    public void setUser2(User user2) {
        this.user2 = user2;
    }

    public Car(String name, double price) {
        super();
        this.name = name;
        this.price = price;
        System.out.println(" 我有引數 ");
    }

    public Car() {

    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Car [name=" + name + ", price=" + price + "]";
    }
}

ioc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

     <bean id="user" class="com.testfan.spring.ioc.User"  scope="prototype">
          <!-- 配置注入屬性 -->
          <property name="name" value="zhangsan"></property>
          <property name="age" value="20"></property>
          <property name="car" ref="cartest"></property>
     </bean>

    <bean class="com.testfan.spring.ioc.Car">
        <!-- 配置注入屬性 -->
        <constructor-arg index="0" value="奧拓"></constructor-arg>
        <constructor-arg index="1" value="1000"></constructor-arg>
    </bean>
</beans>

IocTest.java

//物件關聯
System.out.println(user.getCar());

2.2複雜對像管理
List

<list>
    <ref bean="bean1"/>
    <bean></bean>
</list>

例:

<property name="carList">
    <list>
        <ref bean="cartest" />
        <ref bean="cartest" />  //User擁有多輛車,引用其他bean物件
        <bean class="com.testfan.spring.ioc.Car">  //建立一個新的bean
            <constructor-arg index="0" value="奧拓"></constructor-arg>
            <constructor-arg index="1" value="1000"></constructor-arg>
        </bean>
    </list>
</property>

set:
set和list最大的區別,set會去重

<set>
    <ref bean:bean1/>
    <bean></bean>
</set>

例:

<property name="setlist">
    <set>
        <ref bean="cartest" />
        <ref bean="cartest" />
        <bean class="com.testfan.spring.ioc.Car">
             <constructor-arg index="0" value="奧拓"></constructor-arg>
             <constructor-arg index="1" value="1000"></constructor-arg>
        </bean>
    </set>
</property>

Map:

<map>
  <entry   key:key1  value:value1></entry>
  <entry   key:key2>
       <bean></bean>
  </entry>
</map>

例:

<property name="map">
    <map>
        <entry key="zhangsan" value="111"></entry>  //普通的字串
        <entry key="car" value-ref="cartest"></entry>  //引用bean物件
        <entry key="car2">   //自定義的bean物件
            <bean class="com.testfan.spring.ioc.Car">
                <constructor-arg index="0" value="奧拓"></constructor-arg>
                <constructor-arg index="1" value="1000"></constructor-arg>
            </bean>
        </entry>
    </map>