一个简单的Spring的Ioc的Demo

建立一个model

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


建立一个dao层:

package com.deciphering.dao;

import com.deciphering.model.User;

public interface UserDAO {

	public void save(User user);
}

package com.deciphering.dao.impl;

import com.deciphering.dao.UserDAO;
import com.deciphering.model.User;

public class UserDAOImpl implements UserDAO {

	@Override
	public void save(User user) {

		System.out.println(user.getUsername() + " saved in Oracle!");
		// System.out.println(user.getUsername() + " saved in DB2!");
		// System.out.println(user.getUsername() + " saved in mysql!");

	}

}

建立一个service;

package com.deciphering.service;

import com.deciphering.model.User;

public interface UserService {

	// 处理新增用户业务逻辑
	public void add(User user);
}
package com.deciphering.service;

import com.deciphering.dao.UserDAO;
import com.deciphering.model.User;

public class UserServiceImpl {

	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 UserServiceImpl(UserDAO userDAO) {
		super();
		this.userDAO = userDAO;
	}
}

写一个Spring的bean配置文件


           
  
  
	
  
  	 
  	 
  	 	
  	 
  
 

开始测试:

package com.deciphering.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.deciphering.model.User;

public class UserServiceTest {

	@Test
	public void testAdd() throws Exception {

		final ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		final UserServiceImpl service = (UserServiceImpl) ctx.getBean("userService");

		final User u = new User();

		u.setUsername("测试用户");
		u.setPassword("123456");

		service.add(u);
	}

}

输出:

一月 08, 2017 10:34:34 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5211ef: startup date [Sun Jan 08 22:34:34 CST 2017]; root of context hierarchy
一月 08, 2017 10:34:34 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
一月 08, 2017 10:34:35 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@b0cea2: defining beans [u,userService]; root of factory hierarchy
测试用户 saved in Oracle!

一个简单的Spring的Ioc的Demo_第1张图片

ok

你可能感兴趣的:(SSH)