Spring2.5.6开发环境搭建图文教程
Spring2.5.6开发环境搭建的过程,供大家参考,具体内容如下
1、jar 包准备:
spring 2.5.6 的 jar 包(链接: https://pan.baidu.com/s/1geHM6D9 密码: himj),如图:
commons-logging-1.2(链接: 下载地址),如图:
JUnit 4.7(链接: 下载地址),如图:
2、建立 User Library
2.1 建立 spring 2.5.6 的 User Library
2.1.1 通过路径 Window --> Preferences --> Java --> Build Path --> User Libraries
2.1.2 创建步骤,如下列的图:
这样 spring 2.5.6 Library 就创建好了,以后如果有新的jar包要加进来,可以选中library、点击 Add External JARs进行添加,想加多少加多少。
2.2 建立 JUnit4 的 User Library
2.2.1 通过路径 Window --> Preferences --> Java --> Build Path --> User Libraries
2.2.2 创建步骤,如下列的图:
进入添加User Library 的界面后
建好的两个 Library 如上图。
3、创建相关的一些类和接口,本测试程序创建了 User、UserDAO、UserDAOImpl、UserService,代码如下:
User
package com.bjsxt.model; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
UserDAO
package com.bjsxt.dao; import com.bjsxt.model.User; public interface UserDAO { public void save(User u); }
UserDAOImpl
package com.bjsxt.dao.impl; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserDAOImpl implements UserDAO{ public void save(User u) { System.out.println("a user saved!"); } }
UserService
package com.bjsxt.service; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserService { private UserDAO userDAO; public void addUser(User u){ this.userDAO.save(u); } public UserDAO getUserDAO() { return userDAO; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } }
4、编写与上面类对应的配置文件 beans.xml(名字随便取)
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-2.5.xsd"> <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"></bean> <bean id="userService" class="com.bjsxt.service.UserService"> <property name="userDAO"> <ref bean="u"/> </property> </bean> </beans>
5、编写 spring 测试类:
UserServiceTest
package com.bjsxt.service; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bjsxt.model.User; public class UserServiceTest { @Test public void testAddUser() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");//初始化ApplicationContext对象,加载配置文件beans.xml UserService service = (UserService)ctx.getBean("userService");//从容器中取 User u = new User(); u.setUsername("zhangsan"); u.setPassword("zhangsan"); service.addUser(u);//容器中已经配置了UserDAOImpl了,并把DAOImpl注入到service之中,所以service直接就可以保存了 } }
结果:
代码链接: spring 2.5.6 框架的搭建.zip
上一篇:HashMap插入相同key问题
栏 目:JAVA代码
下一篇:Spring Boot打包war jar 部署tomcat
本文地址:http://www.codeinn.net/misctech/222128.html