原文链接:http://www.orlion.ga/185/
一、下载与安装Spring
2、eclipse中windows->proference->java->bulid path->User libraries创建一个名为Spring的user libraries,导入下载的包中lib目录下如图所示的jar包(commons-logging需要另外下载)
二、使用
创建如图所示代码结构:
UserDAO.java:
package ml.orlion.dao; import ml.orlion.model.User; public interface UserDAO { public void saveUser(User user); }
UserDAOImpl.java
package ml.orlion.dao.impl; import ml.orlion.dao.UserDAO; import ml.orlion.model.User; public class UserDAOImpl implements UserDAO{ public void saveUser(User user){ System.out.println("save usering"); } }
UserService.java
package ml.orlion.service; import ml.orlion.dao.UserDAO; import ml.orlion.dao.impl.UserDAOImpl; import ml.orlion.model.User; public class UserService { private UserDAO userDAO = new UserDAOImpl(); public UserDAO getUserDao() { return userDAO; } public void setUserDao(UserDAO userDAO) { this.userDAO = userDAO; } public void saveUser(User user){ this.userDAO.saveUser(user); } }
User.java
package ml.orlion.model; public class User { private String name; private int age; 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; } }
beans.xml内容:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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"> <bean id="userDao" class="ml.orlion.dao.impl.UserDAOImpl"> </bean> <bean id="userService" class="ml.orlion.service.UserService"> <property name="userDao" ref="userDao"/> </bean> </beans>
现在可以在代码中测试一下Spring了:
SpringTest.java
package ml.orlion.spring; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import ml.orlion.model.User; import ml.orlion.service.UserService; public class SpringTest { public static void main(String[] args){ BeanFactory appContext = new ClassPathXmlApplicationContext("beans.xml"); UserService userService = (UserService)appContext.getBean("userService"); User u = new User(); u.setName("test"); u.setAge(1); userService.saveUser(u); } }
右键运行即可在控制台看到:save usering,成功。