Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0’: Invocation of init method failed; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [WEB-INF/css/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@557a1e2d]]] does not run in a WebApplicationContext but in: org.springframework.context.support.GenericApplicationContext@62ee68d8: startup date [Sun Jul 30 18:48:01 CST 2017]; root of context hierarchy
解决办法是添加如下注解:@WebAppConfiguration(“src/main/resources”)
注解括号的路径是xml配置文件的路径
看报错是静态资源的Handler的ResourceHttpRequestHandler不能创建,正确代码如下:
package space.xxhui;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import space.xxhui.POJO.User;
import space.xxhui.service.UserService;
import java.util.logging.Logger;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/spring-config.xml"})
@WebAppConfiguration("src/main/resources")
public class UserDAOTest3 {
@Autowired
private UserService userService;
private final Logger logger = Logger.getLogger(String.valueOf(getClass()));
@Test
public void TestUserSerivce(){
logger.info("begin........");
User user = new User();
user.setName("Hitvz");
user.setPwd("123456");
User result = userService.checkUser(user);
if(result!=null){
System.out.println(result.toString());
}
logger.info("end........");
}
}
报了如开头引用的错误,这里解释一下:
@WebAppConfiguration注解在类上,
用来声明加载的ApplicationContext是一个WebApplicationContext。
它的属性指定的是Web资源的位置,默认为src/main/webapp
这里把他修改为src/main/resources,指定配置文件路径
所以解决办法就是指定到配置文件的根路径,这里找不到根路径,也就找不到Spring-config.xml的配置吧。所以加上更改根路径的注解@WebAppConfiguration(“src/main/resources”)就好了。
大概意思就是要有根目录:@WebAppConfiguration(“src/main/resources”),接着从根目录找到你的配置文件:@ContextConfiguration({ “classpath:spring/spring-config.xml”})