Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method ‘resourceHandlerMapping’ threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.IllegalStateException: No ServletContext set
SpringConfig.java
@Configuration
@ComponentScan(basePackages = "com.xxx", excludeFilters = @ComponentScan.Filter(
type= FilterType.ANNOTATION, classes= Controller.class))
@PropertySource({"classpath:jdbc.properties", "classpath:log4j.properties"})
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableWebMvc
public class SpringConfig {
}
SpringMvcConfig.java
@Configuration
@ComponentScan(basePackages = {"com.xxx.controller"})
@Import(SpringMvcSupport.class)
public class SpringMvcConfig {
}
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class StudentServiceTest {
@Autowired
private StudentService studentService;
@Test
public void testGetById(){
Student student = studentService.findStudentById(2);
System.out.println(student);
// 规范的做法是进行 assert 判断
}
}
事实上,在非测试环境,上述代码运行正常,但是进入测试阶段就出问题了。根据 Bug 信息搜索相关资料发现,问题集中在两个方面:
第一个问题,@EnableWebMvc 注解和 SpringMvc 相关,应该将其写在 SpringMvcConfig.java 文件上。
第二个问题,在 SpringConfig.java 里,扫描了 com.xxx.config 包,也许产生了容器加载上的问题。因此在 ComponentScan 的写法上,可以采用常规写法,具体到每一个需要扫描的包。
明确了这两个问题,可以将代码调整为:
SpringConfig.java
@Configuration
@ComponentScan(basePackages = {"com.sugarian.service", "com.sugarian.dao"})
@PropertySource({"classpath:jdbc.properties", "classpath:log4j.properties"})
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig {
}
SpringMvcConfig.java
@Configuration
@ComponentScan(basePackages = {"com.xxx.controller"})
@Import(SpringMvcSupport.class)
@EnableWebMvc
public class SpringMvcConfig {
}