@Autowire在java servlet中使用AbstractAnnotationConfigDispatcherServletInitializer

时间:2017-07-08 11:41:24

标签: java spring servlets autowired spring-annotations

我目前正在尝试为spring和Java Web Servlet使用新的基于Java的注释配置。我目前在servlet本身内部使用@Autowired注释时遇到问题,但我不确定它是我的配置文件还是我使用AbstractAnnotationConfigDispatcherServletInitializer来引导servlet配置的错误。

我搜索了论坛,并认为我使用以下代码片段找到了答案:

    public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
  }

然而,调试时似乎是" ServletConfig" - context为null,由于没有注册bean,导致以下错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fdmgroup.bookshop.service.BookService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.processInjection(AutowiredAnnotationBeanPostProcessor.java:387)
at org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(SpringBeanAutowiringSupport.java:110)
at com.fdmgroup.bookshop.controller.HomeController.init(HomeController.java:46)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

我目前不确定@ComponentScan是否未在我的WebConfig类中正确激活,ServletConfig上下文未正确加载,或者其他一些内容正在发挥作用。任何帮助将不胜感激!

WebServlet:

@WebServlet("/")
public class HomeController extends HttpServlet {
private static final long serialVersionUID = 1L;

@Autowired
private BookService bookService;

public HomeController() {
}

public HomeController(BookService bookService) {
    this.bookService = bookService;
}

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
  }


protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List<Book> books = bookService.retrieveAllBooks();
    request.setAttribute("books", books);
    request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}

Java配置文件:

public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getServletConfigClasses() {
    System.out.println("in Servlet Initializer");
    return new Class[] { WebConfig.class };
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { RootConfig.class };
}

}

WebConfig.class:

@Configuration
@EnableWebMvc
@ComponentScan({ "com.fdmgroup.bookshop" })
public class WebConfig extends WebMvcConfigurerAdapter {
}

RootConfig.class:

@Configurable
public class RootConfig {
}

BookService.class:

@Service
public class BookService {
@Autowired
private CRUD<Book> bookRepository;

public BookService(CRUD<Book> bookRepository) {
    this.bookRepository = bookRepository;
}

public BookService() {
}

public void createBook (Book book){
    bookRepository.create(book);
}

public Book retrieveBook (long id){
    return bookRepository.retrieve(id);
}

public void deleteBook (long id){
    bookRepository.delete(id);
}

public List<Book> retrieveAllBooks (){
    return bookRepository.retrieveAll();
}

}

谢谢!

1 个答案:

答案 0 :(得分:1)

对于遇到类似问题的任何人,由于这篇优秀的帖子,我设法解决了自己的问题: getservletconfigclasses-vs-getrootconfigclasses

问题确实与@ComponentScan有关,因为我没有意识到WebConfig仅在Servlet WebApplicationContext中扫描了bean,并且完全单独处理了Root WebApplicationContext。这种新理解的解决方案非常简单,在RootConfig.class中添加了第二个@ComponentScan:

@Configurable
@ComponentScan({ "com.fdmgroup.bookshop" })
public class RootConfig {
}