2 wsxcqesx123 wsxcqesx123 于 2016.04.27 21:26 提问

新人学spring框架xml路径不会填

package spring;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.core.env.StandardEnvironment;
public class DItest{

@SuppressWarnings("resource")  
public static void main(String[] args) {  
    ApplicationContext atx = new ClassPathXmlApplicationContext("beans.xml");  
    UserDao userDao = (UserDao) atx.getBean("userDao");  
    userDao.add();  
}  

}

package spring;

public class UserDao {

private User user;

public void add(){  
    System.out.println("add from userdao");  
    System.out.println(user.toString());  
}  

public User getUser() {  
    return user;  
}  

public void setUser(User user) {  
    this.user = user;  
}  

}

package spring;

public class User {

private String name;

private int age;

private int score;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public int getScore() {

return score;

}

public void setScore(int score) {

this.score = score;

}

public String toString(){  
    return "tostring from user";  
}  

}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">







基本都是抄的代码,想运行试试结果发现报错
Cannot find class [spring.spring.User] for bean with name 'user' defined in class path resource [beans.xml];
应该是路径问题但是改了好多种都不对啊(╯‵□′)╯︵┻━┻,求教

3个回答

zjysource
zjysource   2016.04.28 14:51

学得不精呀。嘻嘻。
ClassPathXmlApplicationContext,如果要用这个,把你的beans.xml放到你的源代码根目录下。
换句话说,看看你的编译目标目录下(比如classes或target),有没有这个文件产生。

wangbailin2009
wangbailin2009   2016.04.29 19:21

把beans.xml贴出来看看,你的User 类在spring package下,那beans.xml中 user bean 就应该这样配置:

<bean id="userDao" class="spring.UserDao">
        <property name="user">
            <ref bean="user"/>
        </property>
</bean>

<bean id="user" class="spring.User"></bean>
u014427391
u014427391   2016.05.01 00:50
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!