通过ApplicationContext.getBean()获取bean实例

spring获取bean容器管理的实例常用方式有两种。

    1.  使用注解注入,@Autowired和@Resource

@Autowired推荐使用构造函数的方式注入,可被@RequiredArgsConstructor代替

@Resource在接口的实现类有多个的时候使用,指定name=实现类名来注入指定的实现类,但@Autowired+@Qualififier也可以实现

    2.  通过ApplicationContext.getBean()获取实例,可通过类名name和类的属性class获取

ApplicationContext.getBean()获取实例对比@Autowired的区别

    1.  @Autowired可触发依赖注入,bean容器中没有该bean,会先注册bean再注入,getBean()没有bean时则返回null

    2.  ApplicationContext.getBean()可获取多例模式bean的实例,使用@Autowired和@Resource注入bean,每次请求的时候都是同一个实例

 1 @RestController
 2 @RequestMapping("/controller")
 3 @RequiredArgsConstructor
 4 public class Controller{    
 5     private final AddOcrService addOcrService;
 6 
 7     @PostMapping("/test")
 8     public void test() {
 9         AddOcrService addOcrService1 = SpringUtils.getBean("addOcrService");
10         System.out.println("test---addOcrService:"+addOcrService);
11         System.out.println("test---addOcrService1:"+addOcrService1);
12     }
13 
14     @PostMapping("/test1")
15     public void test1() {
16         AddOcrService addOcrService1 = SpringUtils.getBean("addOcrService");
17         System.out.println("test1---addOcrService:"+addOcrService);
18         System.out.println("test1---addOcrService1:"+addOcrService1);
19     }
20 }

AddOcrService 类被@Scope("prototype")注解申明为原型模式,下图可以看出通过构造函数注入的addOcrService在多次请求中为同一实例3ef1b7c2,而通过getBean()方式获取的实例addOcrService1每次都不同

 

posted @ 2024-02-16 14:44  leviH  阅读(62)  评论(0编辑  收藏  举报