实现InitializingBean时,Spring MVC Rest API无法正常工作

时间:2016-01-25 02:36:25

标签: spring spring-mvc spring-rest

我有一个基本的API设置与Spring MVC Rest如下。

public abstract class AbstractApi implements InitializingBean {

    @Autowired
    protected ValidatorFactory validatorFactory;

    /* ... */

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(validatorFactory);
    }
}


@Controller
@RequestMapping("books")
public class BookApi extends AbstractApi {

    private final BookRepository bookRepository;

    @Autowired
    public BookApi(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }


    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<Book> getBooks() {
        return new ResponseEntity<>(bookRepository.findAll(), HttpStatus.OK);
    }
}

如果我发送具有上述配置的404 - Not Found请求,服务器将返回GET /books

但是,如果我让AbstractApi取消实施InitializingBean,它就可以了。此外,注释@PostConstructafterPropertiesSet()而不是实施InitializingBean

为什么Spring @Controller API在实施InitializingBean时无效?

2 个答案:

答案 0 :(得分:0)

您的代码看起来是正确的。我自己测试了,一切都按预期工作。我建议的是删除@Autowired ValidatorFactory课程中的AbstractApi仅用于测试目的。实现InitializingBean与请求映射处理程序映射无关。我的工作代码是:

public abstract class AbstractApi implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("after properties set");
    }
}

和我的控制器

@Controller
@RequestMapping("books")
public class BooksController extends AbstractApi {
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<String> getBooks() {
        return new ResponseEntity<>("", HttpStatus.OK);
    }
}

从tomcat开始登录:

2016-01-28 16:48:03.141  INFO 2238 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-01-28 16:48:03.317  INFO 2238 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-01-28 16:48:03.329  INFO 2238 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.23
2016-01-28 16:48:03.405  INFO 2238 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-01-28 16:48:03.405  INFO 2238 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1815 ms
2016-01-28 16:48:03.512  INFO 2238 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-01-28 16:48:03.515  INFO 2238 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
after properties set

答案 1 :(得分:-1)

您当前的@RequestMapping(&#34; books&#34;)路径未正确指定。在端口8080上本地运行时看起来像http://localhost:8080books

应该是@RequestMapping(&#34; / books&#34;) - http://localhost:8080/books

尝试一下。