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
		//NetWork
		System.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" class="com.bczq.service.UserService">
  		<!--<property name="userDAO" ref="userDaoImpl" />-->
  		<constructor-arg>
  			<ref bean="userDaoImpl"/>
  		</constructor-arg>
  	</bean>
  
  	<!-- 声明UserDAOImpl类 -->
  	<bean name="userDaoImpl" class="com.bczq.dao.impl.UserDAOImpl">
  	</bean>
</beans>


6. 进行测试
	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);
	}

你可能感兴趣的:(spring)