1. 什么是spring
2. spring的特性
3. IOC
4. DI
5. AOP
正文:
1. 什么是spring
spring是一个轻量级的开源的框架。
2. spring的特性
spring的特性主要有IOC(控制反转),DI(依赖注入),AOP(面向切面编程)
3. IOC控制反转
在理解控制反转前,先来理解一样,没有spring的话,我们编写代码一般是怎么做的。
先来写一个例子:
未使用spring前的例子
public class Store { private String storeName; private String storeAddress; private String storePhone; public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } public String getStoreAddress() { return storeAddress; } public void setStoreAddress(String storeAddress) { this.storeAddress = storeAddress; } public String getStorePhone() { return storePhone; } public void setStorePhone(String storePhone) { this.storePhone = storePhone; } @Override public String toString() { return "Store{" + "storeName='" + storeName + '\'' + ", storeAddress='" + storeAddress + '\'' + ", storePhone='" + storePhone + '\'' + '}'; } }
先创建java bean store类。然后正常情况下,我们会怎么使用它呢?
public class App { public static void main( String[] args ) { //step1: new store instance Store store = new Store(); //step2: set properties value for store store.setStoreName("永辉超市"); store.setStoreAddress("xx市xxx区xxx路520号"); store.setStorePhone("123456789"); //step3: invoke store tostring method System.out.println(store.toString()); } }
上面的代码中,就是没有使用spring的时候,我们常规情况下是怎么编写代码的。
spring的IOC,看过一个博主这样的介绍,觉得很形象。
IOC:控制反转,就是把创建实例的过程交给spring,就是不用再自己new 对象,只用从sping中获取,而不用自己创建
正转: 自己用对象就自己创建
反转:不在自己创建,而是从spring中直接获取
寿司例子:
我今天想吃寿司,然后呢。
没有spring的话
我要吃寿司——》自己买米,买海带,买寿司醋————》自己做————》吃
有spring的话
我要吃寿司——》寿司店(spring)——》吃
然后来看看,有spring的话,我们会怎么写代码呢?
在main下面新建一个resources目录,resources下面再建一个META-INF目录。里面再建一个applicationContext.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.xsd"> <bean id="hellostore" class="com.emma.test.Store"> <property name="storeName" value="永辉哦"></property> </bean> </beans>
public class App { public static void main( String[] args ) { ApplicationContext ctx= new ClassPathXmlApplicationContext("META-INF/applicationContext.xml"); Store store= (Store) ctx.getBean("hellostore"); System.out.println(store.toString()); } }
综上,这就是IOC