我第一次尝试hibernate + Spring,并在尝试插入数据库时遇到此错误。字符串来自网址或默认值: -
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
InsertTest test = new InsertTest();
test.insert(name);
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
DAO方法是: -
public void insert(String name) {
Resource r=new ClassPathResource("D:\\work\\Spring\\RestAPI\\src\\main\\java\\db\\app.xml");
BeanFactory factory=new XmlBeanFactory(r);
EmployeeDao dao=(EmployeeDao)factory.getBean("d");
Employee e=new Employee();
e.setId(114);
e.setName(name);
e.setSalary(50000);
dao.saveEmployee(e);
}
我收到错误: -
java.lang.IllegalArgumentException: name
at sun.misc.URLClassPath$Loader.findResource(Unknown Source) ~[na:1.8.0_131]
at sun.misc.URLClassPath.findResource(Unknown Source) ~[na:1.8.0_131]
at java.net.URLClassLoader$2.run(Unknown Source) ~[na:1.8.0_131]
at java.net.URLClassLoader$2.run(Unknown Source) ~[na:1.8.0_131]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_131]
at java.net.URLClassLoader.findResource(Unknown Source) ~[na:1.8.0_131]
at org.springframework.boot.loader.LaunchedURLClassLoader.findResource(LaunchedURLClassLoader.java:58) ~[gs-rest-service-0.1.0.jar:0.1.0]
at java.lang.ClassLoader.getResource(Unknown Source) ~[na:1.8.0_131]
at java.net.URLClassLoader.getResourceAsStream(Unknown Source) ~[na:1.8.0_131]
at org.apache.catalina.loader.WebappClassLoaderBase.getResourceAsStream(WebappClassLoaderBase.java:1055) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:166) ~[spring-core-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330) ~[spring-beans-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304) ~[spring-beans-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:79) ~[spring-beans-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:67) ~[spring-beans-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
at main.java.db.InsertTest.insert(InsertTest.java:21) ~[classes!/:0.1.0]
at main.java.hello.GreetingController.greeting(GreetingController.java:23) ~[classes!/:0.1.0]
答案 0 :(得分:0)
与上一个问题相同的问题(下次只是在评论中要求澄清):
Error thrown file does not exist even though it is there
您需要指定此路径:
Resource r = new ClassPathResource("main/java/db/app.xml");
这不是文件系统路径,而是从根包开始的路径。