在tomcat下是正常的,但是用JUnit测试就报错:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, mappedName=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=, description=, name=)}
以解决!
原因:程序需要在初试化的时候读取数据库中的配置信息到ServletContext中,而JUnit中是没有实例化ServletContext的。
解决方法:
1.使用@Autowired(required = false)注解
2.对servletContext进行非空判断,只有不为空才进行下一步操作
@Autowired(required = false)
private ServletContext servletContext;
@PostConstruct
public void startup() {
if (Optional.fromNullable(servletContext).isPresent()) {
servletContext.setAttribute(PAGE_SIZE, getConfig(PAGE_SIZE));
}
}