Mat*_*ano 11 java spring tomcat spring-boot
我有一个使用spring-boot和嵌入式Tomcat容器的应用程序.
据我所知,我的代码与spring-boot 示例项目相同.但是,当我运行我的测试时,我得到的是404而不是200(在我尝试发布的情况下,而不是让我收到405,这与Tomcat设置错误一致):
Failed tests:
UserControllerTest.testMethod:45 Status expected:<200> but was:<404>
Run Code Online (Sandbox Code Playgroud)
我的基于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");
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
UserController.java:
@RestController
@RequestMapping("/")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> testMethod() {
return new ResponseEntity<>("Success!", HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
有什么基本的东西我不见了吗?我没有提供自己的Mvc配置,我没有触及Spring MVC DispatcherServlet,所以我假设spring-boot会自动配置Tomcat.
Mat*_*ano 16
事实证明问题是组件扫描配置.即使@ComponentScan使用了注释,控制器也在一个单独的包中,因此Spring从未将其包含在调度程序中.
添加@ComponentScan(basePackages = "com.my.controller"))解决了我的问题.
| 归档时间: |
|
| 查看次数: |
8628 次 |
| 最近记录: |