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;}}
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;}}
package com.bczq.dao;import com.bczq.pojo.User;public interface UserDAO {public void save(User user);}
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!");}}
<?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);}