美文网首页
在非spring管理的类中如何调用spring自动装配管理的实体

在非spring管理的类中如何调用spring自动装配管理的实体

作者: haiyong6 | 来源:发表于2019-11-13 21:48 被阅读0次

    有些时候不但需要在controller层中调用业务service接口去执行查询数据库的内容,而且还会在普通类中调用,也就是没有加入@controller注解 没有被spring自动装配管理的普通类中如何调用spring管理的类呢,比如有时候会在filter过滤器中需要调用spring管理的业务方法实现查询数据库的操作。

    可以通过spring-web.jar中提供的org.springframework.web.context.support.WebApplicationContextUtils来获取应用上下文,其中的request是HttpServletRequest:

                ServletContext context = request.getServletContext();
                ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
                UserInfoService userInfoService = ctx.getBean(UserInfoService.class);
                UserInfoVo userInfoVo = userInfoService.getUserByUserId(request.getParameter("userId"));
    

    如此就可以拿到数据库中查询的user信息了

    另外普通的spring项目中java读取applicationContext.xml的代码如下,同样也可以直接拿到spring上下文

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserLogMapper userLogMapper = (UserLogMapper)applicationContext .getBean("userLogMapper")//拿到装配的实体类
    //UserLogMapper userLogMapper = applicationContext .getBean(UserLogMapper.class); 此处等于上面的代码
    

    相关文章

      网友评论

          本文标题:在非spring管理的类中如何调用spring自动装配管理的实体

          本文链接:https://www.haomeiwen.com/subject/tcahictx.html