• Spring Bean Scope Prototype


    Spring Bean Scope Prototype

    pring Bean Scope Prototype

    Posted on: August 30, 2010 at 12:00 AM


    In this tutorial you will learn about Spring Bean Scope Prototype
    Spring Bean Scope

    There are five different types of bean scopes (i.e. singleton, prototype,
    request, session, global session) supported by the spring framework. Apart of
    these five the Spring?s core scope is singleton and prototype. The singleton
    return a single bean instance per spring IoC container and the prototype return
    a new bean instance each time when requested. In this example it demonstrate the
    concept of prototype.

    SimpleBean.java

    package spring.bean.scope.singleton;

    public class SimpleBean {
            String message;

            public String getMessage() {
                    return message;
            }

            public void setMessage(String message) {
                    this.message = message;
            }
    }

    AppMain.java

    package spring.bean.scope.prototype;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import spring.bean.scope.prototype.SimpleBean;

    class AppMain {
            public static void main(String[] args) {
                    ApplicationContext context = new ClassPathXmlApplicationContext(
                                    new String[] { "context.xml" });

                    SimpleBean bean1 = (SimpleBean) context.getBean("simplebean2");
                    bean1.setMessage("Message by bean1");
                    System.out.println("Message : " + bean1.getMessage());

                    SimpleBean bean2 = (SimpleBean) context.getBean("simplebean2");
                    System.out.println("Message : " + bean2.getMessage());
            }
    }

    context.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" xmlns:aop="http://www.springframework.org/schema/aop"

      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

     

    <!-- prototype -->

    <bean id="simplebean2" class="spring.bean.scope.prototype.SimpleBean" scope="prototype"/>

     

    </beans>



    When you run this application it will display message as shown below:


    Message : Message by bean1

    Message : null
  • 相关阅读:
    python格式化输出之format用法
    Mybatis插入数据返回主键
    DBC 和 Mybatis连接mysql数据库的时候,设置字符集编码
    工具列表
    Idea的Git如何回退到上一个版本
    mybatis-plus id主键生成的坑
    JAVA 线上故障排查完整套路,从 CPU、磁盘、内存、网络、GC 一条龙!
    DDD-快速hold住业务的利器
    深入理解ThreadLocal的原理和内存泄漏问题
    VUE开发--环境配置
  • 原文地址:https://www.cnblogs.com/lexus/p/2527850.html
Copyright © 2020-2023  润新知