天天看點

springboot中怎麼擷取多例(prototype)

平時我們使用springboot注入的類,預設是單例的。

是以需要在注入的時候聲明是原型模式(prototype)

@Component
@Scope("prototype")
public class User1 {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
           

但是當使用時,使用了@Autowired注解來擷取spring管理的對象 ,每次請求擷取的一直是同一個對象。

例子:

@RestController
@RequestMapping("test")
public class TestController {
    @Autowired
    private User1 user1;
    private static int num=0;
    @GetMapping("scope1")
    public void testScope1(){
        System.out.println("num:"+ ++num +"次請求,"+user1);
    }

}
           

請求結果:

num:1次請求,[email protected]
num:2次請求,[email protected]
           

可以實作多例的方式很多,找一個比較簡單的寫法。

通過

@RestController
@RequestMapping("test")
public class TestController {
    private static int num=0;
    @Autowired
    private  ApplicationContext context;
   
    @GetMapping("scope2")
    public void testScope2(){
        System.out.println("num:"+ ++num +"次請求,"+  context.getBean("user1"));
    }
}
           

請求結果:

num:3次請求,[email protected]
num:4次請求,[email protected]
           

解決使用@Autowired導緻多例無效的問題。

繼續閱讀