微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – spring-boot w /嵌入式tomcat不会向控制器发送请求

我有一个使用 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");
            }
        };
    }
}

UserController.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注释,控制器也在一个单独的包中,所以Spring从未将它包含在调度程序中.

添加@ComponentScan(basePackages =“com.my.controller”))解决了我的问题.

原文地址:https://www.jb51.cc/java/121954.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐