011. Spring Bean单例与非单例

来源:互联网 发布:mac页面比例缩小快捷键 编辑:程序博客网 时间:2024/05/18 20:12

1、创建Java项目:File -> New -> Java Project

2、引入必要jar包,项目结构如下
这里写图片描述

3、创建People实体类People.java

package com.spring.model;public class People {    private int id;    private String name;    public People() {        super();        System.out.println("Create People");    }    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;    }    @Override    public String toString() {        return "People [id=" + id + ", name=" + name + "]";    }}

4、创建spring配置文件applicationContext.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="prototypePeople" class="com.spring.model.People" scope="prototype">        <property name="id" value="0"></property>        <property name="name" value="prototypePeople"></property>    </bean>    <!--单例模式,加载applicationContext.xml时初始化对象-->    <bean id="singletonPeople" class="com.spring.model.People" scope="singleton">        <property name="id" value="0"></property>        <property name="name" value="singletonPeople"></property>    </bean></beans>

5、创建Spring测试类SpringUnit.java

package com.spring.junit;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringUnit {    ClassPathXmlApplicationContext ctx = null;    @Before    public void setUp() throws Exception {        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");    }    @Test    public void test() {        System.out.println(ctx.getBean("prototypePeople") == ctx.getBean("prototypePeople"));        System.out.println(ctx.getBean("singletonPeople") == ctx.getBean("singletonPeople"));    }    @After    public void tearDown() throws Exception {        ctx.close();    }}

6、测试结果

... 省略Spring日志信息 ...Create PeopleCreate PeopleCreate Peoplefalsetrue... 省略Spring日志信息 ...
原创粉丝点击