Springboot> WebServlet - 传递弹簧容器

时间:2017-04-13 22:26:00

标签: spring servlets spring-boot

我有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;
}

@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中为null,如果我在我的servlet中为bASpeechletHandler设置对象并继续移动,那么bASpeechletHandler中的组件,服务和存储库也为null。 感谢。

2 个答案:

答案 0 :(得分:2)

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

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

2.在 BASpeechletHandler 类中添加 @Component注释中的一个。

这将使该类符合自动发现 bean的条件。

答案 1 :(得分:0)

问我可能有点复杂。我找到了解决方案。在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");
    }

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"); }

感谢。