一、spring由来
java现有技术已经足够使用,但如何将这些技术进行整合,简化使用过程,由此spring框架诞生。
二、简单示例:简单了解spring思想(上层调用下层:Action层---service层---dao层)
dao层:
(1)interface:UserDao
package userdao;
public interface UserDao {
public void getUser();
}
(2)impclass1:UserDaoImp
package userdaoimp;
import userdao.UserDao;
public class UserDaoImp implements UserDao{
public void getUser(){
System.out.println("获取数据!");
}
}
impclass2:UserDaoMySqlImp
package userdaoimp;
import userdao.UserDao;
public class UserDaoMySqlImp implements UserDao{
@Override
public void getUser() {
System.out.println("获取MySql数据");
}
}
service层:
(1)interfface:service
package service;
public interface Service {
public void getUser();
}
(2)impclass:UserServiceImp
package serviceimp;
import service.Service;
import userdao.UserDao;
import userdaoimp.UserDaoImp;
public class ServiceImp implements Service{
/*
* 原方法:
* UserDaoImp userdaoimp=new UserDaoImp();
UserDaoImp userdaomysqlimp=new UserDaoMySqlImp();
原来的写法,new 一个UserDaoImp对象,然后调用其方法
对象是自己创建的,所以当代码发生改变时(变为UserDaoMySqlImp()),要改变源码
*
*
*/
private UserDao userdaoimp=null;
public void setUserDao(UserDao userdaoimp){
this.userdaoimp=userdaoimp;
}
public void getUser(){
userdaoimp.getUser();
}
}
Action层:
package test;
import service.Service;
import serviceimp.ServiceImp;
import userdaoimp.UserDaoImp;
import userdaoimp.UserDaoMySqlImp;
public class Test {
public static void main(String[] args) {
ServiceImp serviceimp=new ServiceImp();
serviceimp.setUserDao(new UserDaoMySqlImp());
serviceimp.getUser();
serviceimp.setUserDao(new UserDaoImp());
serviceimp.getUser();
}
}
有错误欢迎指教!