赞
踩
springboot 使用工厂+反射创建bean示例,创建的bean实例默认为单例,可通过注解@Scope("prototype")使得每次调用对象的时候生成一个新的对象
********************************
pojo 层
- @Component
- @Scope("singleton")
- public class Person {
-
- private String name;
- private Integer age;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
-
- @Override
- public String toString() {
- return this.name+" "+this.age+" "+super.toString();
- }
- }
**************************************
controller 层
- @RestController
- public class HelloController {
-
- @Resource
- private Person person;
-
- @Resource
- private Person person2;
-
- @RequestMapping("/hello")
- public String hello(){
- person.setName("瓜田李下");
- person.setAge(24);
- System.out.println(person);
-
- return person.toString();
- }
-
- @RequestMapping("/hello2")
- public String hello2(){
- System.out.println(person2);
-
- return person2.toString();
- }
- }
调用/hello 、/hello2后,控制台输出
@Scope("singleton"):scope的默认值
- 瓜田李下 24 com.example.demo.pojo.Person@79ea6d7a
- 瓜田李下 24 com.example.demo.pojo.Person@79ea6d7a
@Scope("prototype")
- 瓜田李下 24 com.example.demo.pojo.Person@58b44e01
- null null com.example.demo.pojo.Person@2e3371d3
说明:springboot的prototype创建的对象不会复制bean的数据内容,属性都为默认值
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。