我有一个使用 spring-boot 和嵌入式 Tomcat 容器的应用程序。
据我所知,我的代码与 spring-boot sample project 相同.但是,当我运行测试时,我得到的是 404 而不是 200(在我尝试发布而不是获取的情况下,我收到 405,这与 Tomcat 设置不正确一致):
Failed tests:
UserControllerTest.testMethod:45 Status expected:<200> but was:<404>
我的基于 Java 的配置(省略了一些配置类):
@Configuration
@ComponentScan
@EnableAutoConfiguration
@Import({ ServiceConfig.class, DefaultRepositoryConfig.class })
public class ApplicationConfig {
private static Log logger = LogFactory.getLog(ApplicationConfig.class);
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class);
}
@Bean
protected ServletContextListener listener() {
return new ServletContextListener() {
@Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("ServletContext initialized");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
logger.info("ServletContext destroyed");
}
};
}
}
用户 Controller .java:
@RestController
@RequestMapping("/")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> testMethod() {
return new ResponseEntity<>("Success!", HttpStatus.OK);
}
}
UserControllerTest.java:
RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {ApplicationConfig.class})
public class UserControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
@Test
public void testMethod() throws Exception {
this.mockMvc.perform(get("/")).andExpect(status().isOk());
}
}
我缺少一些基本的东西吗?我没有提供自己的 MVC 配置,也没有接触过 Spring MVC DispatcherServlet,所以我假设 spring-boot 会自动配置 Tomcat。
最佳答案
原来问题出在组件扫描配置上。尽管使用了 @ComponentScan
注释,但 Controller 位于单独的包下,因此 Spring 从未将其包含在调度程序中。
添加 @ComponentScan(basePackages = "com.my.controller"))
解决了我的问题。
关于java - 带有嵌入式tomcat的spring-boot不会将请求分派(dispatch)给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22547117/