【问题标题】:Springboot>WebServlet - Pass spring containerSpring Boot>Web Servlet - 传递 spring 容器
【发布时间】:2017-04-13 22:25:59
【问题描述】:

我有 springBoot 独立应用程序。我在我的独立应用程序中使用了@SpringBootApplication、@ServletComponentScan 注释。我所有的组件,bean 在 spring 容器中初始化并在应用程序启动时打印。

在我的 servlet 中,我调用了处理程序,并且 bean 以 null 的形式出现。我如何通过我的 servlet 传递 spring 容器?

@SpringBootApplication
@ServletComponentScan
public class AStandaloneApplication {
  public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(AStandaloneApplication.class, args);
  }
}

@WebServlet("/ba")
public class BAServlet extends SpeechletServlet {

    @Autowired
    private BASpeechletHandler bASpeechletHandler;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.setSpeechlet(bASpeechletHandler);
    }   
}

public class BASpeechletHandler implements Speechlet {
  @Autowired
    private BSEngine bSEngine;      

        @Autowired
    private IBotResponseObjToAlexaSpeechletResponseObj botResponseObjToAlexaSpeechletResponseObj;
}

bASpeechletHandler 在 servlet 中为空,如果我在我的 servlet 中为 bASpeechletHandler 设置对象并继续前进,那么 bASpeechletHandler 中的组件、服务和存储库也为空。 谢谢。

【问题讨论】:

  • 如果你使用的是Servlet,它不再是独立的了,分享你的代码
  • 嗨@SundararajGovindasamy,谢谢。我用代码 sn-p 更新了问题

标签: spring servlets spring-boot


【解决方案1】:

1.将包添加到组件扫描 - 类似

@ServletComponentScan(basePackages="org.my.pkg")

2.将其中一个 @Component 注释添加到您的BASpeechletHandler 类中。

这将使该类有资格自动发现 bean。

【讨论】:

  • 不走运。当我打印在主类中注册的 bean / 组件时,它通过注释 servletComponentScan 打印所有组件和服务。但是,在 servlet 内部,这仍然是组件/bean 基于组件名称/beanName 显示 null。
  • 我找到了答案。 public void init(ServletConfig config) 抛出 ServletException { super.init(); appContext = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); bASpeechletHandler = (bASpeechletHandler) appContext.getBean("bASpeechletHandler"); }
【解决方案2】:

问起来可能有点麻烦。我找到了解决方案。在 Web applicationContext 中,我 ping 了 spring 上下文并获得了 bean。

private ApplicationContext appContext;
private BASpeechletHandler bASpeechletHandler;

public void init(ServletConfig config) throws ServletException {
        super.init();
        appContext = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        bASpeechletHandler = (bASpeechletHandler) appContext.getBean("bASpeechletHandler");
    }

谢谢。

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 2022-10-14
    • 1970-01-01
    • 2017-11-17
    • 2013-02-25
    • 2014-07-13
    • 2017-09-20
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多