一、原型模式在 Spring 框架中源码分析
1、Spring 中原型 bean 的创建,就是原型模式的应用;
2、代码分析+Debug 源码
3、代码
1 public class Monster {
2
3 private Integer id = 10 ;
4 private String nickname = "牛魔王";
5 private String skill = "芭蕉扇";
6 public Monster() {
7
8 System.out.println("monster 创建..");
9 }
10 public Monster(Integer id, String nickname, String skill) {
11 //System.out.println("Integer id, String nickname, String skill被调用");
12 this.id = id;
13 this.nickname = nickname;
14 this.skill = skill;
15 }
16
17 public Monster( String nickname, String skill,Integer id) {
18
19 this.id = id;
20 this.nickname = nickname;
21 this.skill = skill;
22 }
23 public Integer getId() {
24 return id;
25 }
26 public void setId(Integer id) {
27 this.id = id;
28 }
29 public String getNickname() {
30 return nickname;
31 }
32 public void setNickname(String nickname) {
33 this.nickname = nickname;
34 }
35 public String getSkill() {
36 return skill;
37 }
38 public void setSkill(String skill) {
39 this.skill = skill;
40 }
41 @Override
42 public String toString() {
43 return "Monster [id=" + id + ", nickname=" + nickname + ", skill="
44 + skill + "]";
45 }
46
47
48 }
49 -------------------------Test类---------------------
50 public class ProtoType {
51
52 public static void main(String[] args) {
53 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
54 // 获取monster[通过id获取monster]
55 Object bean = applicationContext.getBean("id01");
56 System.out.println("bean" + bean); // 输出 "牛魔王" .....
57
58 Object bean2 = applicationContext.getBean("id01");
59
60 System.out.println("bean2" + bean2); //输出 "牛魔王" .....
61
62 System.out.println(bean == bean2); // false
63
64 // ConfigurableApplicationContext
65 }
66
67 }
配置文件:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 <!-- 这里我们的 scope="prototype" 即 原型模式来创建 -->
6 <bean id="id01" class="com.java.spring.bean.Monster"
7 scope="prototype"/>
8 </beans>