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
image.png
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">
    </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
原因:prototype 每次创建新的对象

二、对象赋值

property属性注入
2.1 基本属性
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 对象关联

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最大的区别,setlist会去重

<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>

代码地址:https://github.com/HopeWing1286/SpringMvc.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容