一:Spring基本概念
1.spring是容器框架,创建bean,并维护bean之间的关系,即Spring包含并管理应用对象的配置和生命周期,在这个意义上它是一种容器,你可以配置你的每个bean如何被创建–基于一个可配置原型(prototype),你的bean可以创建一个单独的实例或者每次需要时都生成一个新的实例–以及它们是如何相互关联的。
2.spring可以管理web层,持久层,业务层。spring可以配置各
个层的组件并且维护各个层之间的关系。
二:核心原理之IOC
IOC控制反转(Inversion Of Control),意义等同于 DI(Dependency Injection)。
概念:控制权由对象本身转向容器,由容器根据配置文件创建 对象实例并实现各个对象之间的依赖关系。
即Spring通过一种称作控制反转(IoC)的技术促进了低耦合。当应用了IoC,一个对象依赖的其它对象会通过被动的方式传递进来,而不是这个对象自己创建或者查找依赖对象。你可以认为IoC与JNDI相反–不是对象从容器中查找依赖,而是容器在对象初始化时不等对象请求就主动将依赖传递给它。
核心:bean工厂。
三:入门案例
当编写一个模拟储存账户功能时,如下所示,需要先在持久层完成功能,业务层调用持久层,表现层调用业务层:
//账户持久层实现类
public class AccountDaoImpl implements AccountDao{
public void saveAccount(){
System.out.println("账户保存成功!");
}
}
//账户业务层实现类
public class AccountServicesImpl implements AccountServices {
private AccountDao accountDao = new AccountDaoImpl();
public void saveAccount(){
accountDao.saveAccount();
}
}
//账户表现层实现类
public class Client {
public static void main(String[] args) {
AccountServices accountServices = new AccountServicesImpl();
accountServices.saveAccount();
}
}
可见类与类之间的依赖也就是耦合度比较高,于是我们需要引入第三方,将控制权交给第三方来降低类之间的耦合度。
使用spring控制反转思想之后:
创建一个配置文件,用于保存持久层和表现层实现类对象的创建语句:
accountServices=com.itheima.services.impl.AccountServicesImpl
accountDao=com.itheima.dao.impl.AccountDaoImpl
bean工厂思想:
public class FactoryBean {
//定义一个properties对象
private static Properties properties;
//定义一个Map来保存对象
private static Map<String,Object> beans;
//使用静态代码块为properties对象赋值
static {
try {
//实例化properties对象
properties = new Properties();
//使用类加载器获取properties文件的流对象
InputStream inputStream = FactoryBean.class.getClassLoader().getResourceAsStream("bean.properties");
//加载配置文件
properties.load(inputStream);
//实例化容器
beans = new HashMap<String,Object>();
//取出配置文件中所有的key
Enumeration<Object> keys = properties.keys();
//遍历枚举
while(keys.hasMoreElements()){
//取出每个key
String key = keys.nextElement().toString();
//根据Key获取value
String beanPath = properties.getProperty(key);
System.out.println(beanPath);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器
beans.put(key, value);
}
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
根据bean的名称获取bean对象
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}
}
//账户业务层实现类
public class AccountServicesImpl implements AccountServices {
private AccountDao accountDao = (AccountDao) FactoryBean.getBean("accountDao");
public void saveAccount(){
accountDao.saveAccount();
}
}
//账户表现层实现类
public class Client {
public static void main(String[] args) {
AccountServices accountServices = (AccountServices) FactoryBean.getBean("accountServices");
accountServices.saveAccount();
}
}