【问题标题】:Spring Boot - access component inside a servletSpring Boot - servlet 中的访问组件
【发布时间】:2015-08-25 17:00:20
【问题描述】:

我有一个 Spring Boot 应用程序,它为我的基于球衣的 API 提供服务。我需要让服务层将 blob 数据作为流提供给客户端。我编写了一个 servlet 来做到这一点,并将其配置如下。

    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        return new ServletRegistrationBean(new BlobReaderServlet(),"/blobReader/*");
    }

但是,在 servlet 代码中,我似乎无法注入任何组件(它们都是空的)。我需要注入一个实际从数据库加载 blob 数据的组件。

@WebServlet(name = "BlobReaderServlet",
        urlPatterns = {"/blobreader"})
@Component
public class BlobReaderServlet extends HttpServlet {

    Logger logger = Logger.getLogger(this.getClass().getName());

    @Inject
    DocumentLoaderComponent blobLoader;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

我强烈怀疑 servlet 毕竟不是 Spring 管理的组件,并且依赖注入不起作用。如何从上下文中访问组件?

更新

这比我想象的要简单得多。

@Override
    public void init() throws ServletException {
        ApplicationContext ac = (ApplicationContext) getServletConfig().getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        this.documentBlob = (DocumentBlob) ac.getBean("documentBlobBean");
    }

【问题讨论】:

    标签: spring servlets spring-boot


    【解决方案1】:

    您的 servlet 不是 Spring 托管 bean 是正确的。那是因为您正在直接实例化实例(即,在您的 bean 方法中调用 new BlobReaderServlet())。另一种解决方案是按如下方式更改您的配置类:

    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        return new ServletRegistrationBean(blobReaderServlet(),"/blobReader/*");
    }
    
    @Bean
    public BlobReaderServlet blobReaderServlet(){
        return new BlobReaderServlet();
    }
    

    这将允许 Spring 管理实例并对其执行自动装配。

    【讨论】:

      猜你喜欢
      • 2014-05-29
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      相关资源
      最近更新 更多