前段时间学了Spring框架,简单说一下我的理解。这篇博客全篇是大白话讲述,适合初学者理解,或者学前了解。主页中也有Spring的超详细的学习笔记和代码,方便大家学习。
Spring理解
Spring的核心:IOC(存放对象的map集合)和AOP(更方便的在方法的前后左右添加各种操作)
Spring的优点:免费、好用。
IOC
IOC理解(婚介所)
把IOC想象成一个婚介所:
1、在没有婚介所(没有IOC)之前,需要自己找对象(new一个对象),比较麻烦。
2、有了婚介所(有IOC)以后,就不需要自己找对象了,婚介所会帮你找,比较方便。
IOC如何使用(找对象过程)
1、建立婚介所(导入相关的jar包)
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
commons-logging-1.1.3.jar Spring运行的时候依赖一个日志包,没有就报错;
2、注册为婚介所会员(配置Spring的bean的配置文件)
<bean id="person" class="com.atguigu.bean.Person">
<!--使用property标签为Person对象的属性赋值
name="lastName":指定属性名
value="张三":为这个属性赋值
-->
<property name="lastName" value="张三"></property>
<property name="age" value="18"></property>
<property name="email" value="zhangsan@qq.com"></property>
<property name="gender" value="男"></property>
</bean>
3、找对象(使用Spring的单元测试进行测试)
//ApplicationContext:代表ioc容器
//ClassPathXmlApplicationContext:当前应用的xml配置文件在 ClassPath下
//根据spring的配置文件得到ioc容器对象
ApplicationContext ioc = new ClassPathXmlApplicationContext("ioc.xml");
//容器帮我们创建好对象了;
Person bean = (Person) ioc.getBean("person");
System.out.println(bean);
AOP
AOP理解(ATM取钱)
想象自己在ATM取钱
1、如果没有AOP:在取钱之前需要输入密码之后,才能拿到钱,比较麻烦。
2、如果有了AOP:就相当于带着自己的老婆去取钱(不需要自己进行密码输入),老婆就帮你进行用户验证,你只管拿钱就好,比较方便。
简而言之:取钱(方法)之前(之后,异常,结束),老婆(AOP)替你执行一些操作(方法)。
AOP如何使用
1、导包
commons-logging-1.1.3.jar
spring-aop-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
Spring支持面向切面编程的包是:
spring-aspects-4.0.0.RELEASE.jar:基础版
加强版的面向切面编程(即使目标对象没有实现任何接口也能创建动态代理)
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
2、写配置;
只需要在方法(你拿钱)上,添加注解(@Before@After@AfterThrowing@AfterReturning)即可。
各注解的作用:
@Before:在方法执行之前(你拿钱之前让老婆输入密码)
@After:方法结束之后(你拿完钱后安全回家,老婆高兴)
@AfterThrowing:方法异常时(你拿钱时,钱卡机。。。老婆生气)
@AfterReturning:方法正常返回后(你拿到钱让老婆回家)
3、测试