在servlet中使用spring注解@Autowired自动注入bean

一,使用@Autowired注入需要使用的bean。

   @Autowired
    private  InstitutionService institutionService;
    
    @Autowired
    private UserService service;

二,使用spring提供的获取bean的工具类来加载自动注入

WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getAutowireCapableBeanFactory().autowireBean(this); 

注:该方法使用在重写的 init 方法中(只调用该servlet一次可以使用。并且使用于初始化方法。第二次调用依然没有注入)。

猜你喜欢

转载自blog.csdn.net/weixin_41929877/article/details/81451112