Spring3.2.2 HelloWorld

根据原始文档Spring Framework Reference Documentation来建立Spring HelloWorld。

下面是Java工程的目录以及所需的jar包:

Spring3.2.2 HelloWorld
 

1.在src目录下建立beans.xml文件,并从spring Framework Reference Documentation中Core Technologies  -> Configuration metadata拷贝配置文件到该文件中,然后根据需要修改配置文件

<?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="userDaoImpl" class="com.bjsxt.dao.impl.UserDAOImpl">
    <!-- collaborators and configuration for this bean go here -->
  </bean>

  <bean id="userService" class="com.bjsxt.service.UserService">
     <property name="userDAO" ref="userDaoImpl" />
    <!-- collaborators and configuration for this bean go here -->
  </bean>

  <!-- more bean definitions go here -->

</beans>
 

2.接口UserDao

package com.bjsxt.dao;
import com.bjsxt.model.User;


public interface UserDAO {
	public void save(User user);
}

 

3.接口UserDao的实现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 user) {

		System.out.println("user saved!");
	}

}
 

4.编写一个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;
	}
}
 

5.编写UserService

package com.bjsxt.service;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.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;
	}
}

 

6.编写测试代码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;

//Dependency Injection
//Inverse of Control
public class UserServiceTest {

	@Test
	public void testAdd() {
		/*ApplicationContext是建立在BeanFactory之上的,BeanFactory它只是完成了Bean工厂的一些功能,像
		 *Bean的声明周期它都处理不了。而ApplicationContext除了能完成BeanFactory所有的功能之外,还能够完成
		 *一些其他的附加的功能,比如说bean的声明的周期。
		 */
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

		UserService service = (UserService)ctx.getBean("userService");

		User u = new User();
		u.setUsername("zhangsan");
		u.setPassword("zhangsan");
		service.add(u);
	}

}

你可能感兴趣的:(helloworld)