首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

Spring 简略小例子

2012-09-09 
Spring 简单小例子1. 定义基本的目录逻辑1. 要进行操作的用户类package com.bczq.pojopublic class User

Spring 简单小例子
1. 定义基本的目录逻辑

1. 要进行操作的用户类

package com.bczq.pojo;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;}}

2. 对User进行管理的服务类
package com.bczq.service;import com.bczq.dao.UserDAO;import com.bczq.pojo.User;public class UserService {private UserDAO userDAO;  public void add(User user) {userDAO.save(user);}public UserDAO getUserDAO() {return userDAO;}public void setUserDAO(UserDAO userDAO) {this.userDAO = userDAO;}public UserService(UserDAO userDAO) {super();this.userDAO = userDAO;}}


3. 对User进行操作的Dao层
package com.bczq.dao;import com.bczq.pojo.User;public interface UserDAO {public void save(User user);}


4. 对User进行操作的Dao层实现类
package com.bczq.dao.impl;import com.bczq.dao.UserDAO;import com.bczq.pojo.User;public class UserDAOImpl implements UserDAO {public void save(User user) {//Hibernate//JDBC//XML//NetWorkSystem.out.println("user saved!");}}


5. 编写配置文件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">           <!-- 声明UserService类,当其初始化时候会自动初始化ref所指向的name(id)对应的bean --> <bean id="userService" ref="userDaoImpl" />-->  <constructor-arg>  <ref bean="userDaoImpl"/>  </constructor-arg>  </bean>    <!-- 声明UserDAOImpl类 -->  <bean name="userDaoImpl" name="code">public static void main (String [] arg){ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");// 获得service对象UserService service = (UserService)ctx.getBean("userService");User u = new User();u.setUsername("zhangsan");u.setPassword("zhangsan");service.add(u);}

热点排行