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];
应该是路径问题但是改了好多种都不对啊(╯‵□′)╯︵┻━┻,求教
学得不精呀。嘻嘻。
ClassPathXmlApplicationContext,如果要用这个,把你的beans.xml放到你的源代码根目录下。
换句话说,看看你的编译目标目录下(比如classes或target),有没有这个文件产生。
把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>
您可以看看我的博客:http://blog.csdn.net/u014427391/article/details/50621111