原型模式——Spring源码分析

原型模式在Spring框架中源码分析

1 Spring中原型bean的创建,就是原型模式的应用

Monster

dart 复制代码
package com.baidu.spring.bean;
public class Monster {
    private Integer id = 10;
    private String nickname = "牛魔王";
    private String skill = "芭蕉扇";

    public Monster() {
        System.out.println("monster 创建 ..");
    }

    public Monster(Integer id, String nickname, String skill) {
        this.id = id;
        this.nickname = nickname;
        this.skill = skill;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getSkill() {
        return skill;
    }

    public void setSkill(String skill) {
        this.skill = skill;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "id=" + id +
                ", nickname='" + nickname + '\'' +
                ", skill='" + skill + '\'' +
                '}';
    }
}

ProtoType

dart 复制代码
package com.baidu.spring.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ProtoType {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        Object bean = applicationContext.getBean("id01");
        System.out.println("bean = " + bean);

        Object bean2 = applicationContext.getBean("id01");
        System.out.println("bean2 = " + bean2);

        System.out.println(bean == bean2);


    }

}
复制代码
bean.xml
dart 复制代码
<?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="id01" class="com.baidu.spring.bean.Monster" scope="prototype" />

</beans>

debug执行

相关推荐
咖啡八杯4 小时前
GoF设计模式——状态模式
java·面试·架构
荣码4 小时前
Prompt工程实战:同一个需求换3种写法,效果差10倍
java·python
weixin_422329314 小时前
AgentScope Java ReActAgent 核心循环深度解析
java·开发语言·人工智能
952364 小时前
RabbitMQ - 高级特性
java·spring boot·分布式·后端·rabbitmq
尽兴-4 小时前
传统 Java/Vue 系统如何一步步接入 AI 维护
java·vue.js·人工智能·ai·大模型
shuoshuohaohao4 小时前
《HTTP协议》
java·web
zzz_23684 小时前
【Java实习面试算法冲刺】图论
java·算法·面试
一路向北North5 小时前
Spring Security OAuth2.0(22):分布式系统授权-搭建网关
java·后端·spring
存在的五月雨5 小时前
SpringBoot后端限制重复提交
java·spring boot·后端
Sam_Deep_Thinking5 小时前
一次线程池线上故障复盘:四层防线如何避免数据丢失
java·面试·程序员