spring的IOC和AOP
spring是一个基于IOC和AOP的结构J2EE系统的框架。
是一个轻量级的 DI / IoC 和 AOP 容器的开源框架,来源于 Rod Johnson 在 >其著作《Expert one on one J2EE design and development》中阐述的部分理念>和原型衍生而来。
Spring 提倡以“最少侵入”的方式来管理应用中的代码,这意味着我们可以随时安装
或者卸载 Spring
适用范围:任何 Java 应用
Spring 的根本使命:简化 Java 开发
IOC反转控制是Spring的基础,就是说创建对象由以前的程序员自己new构造方法来调用转变为了交由Spring创建对象,比如转移交给了IoC容器,它就是一个专门用来创建对象的工厂,你要什么对象,它就给你什么对象,有了 IoC容器,依赖关系就变了,原先的依赖关系就没了,它们都依赖IoC容器了,通过IoC容器来建立它们之间的关系。**其不是什么技术,而是一种设计思想。**其中DI(依赖注入)其实就是IOC的一种类型,还有一种是DL(Dependency Lookup依赖查找)。 DL由Martin Fowler 在2004年初的一篇论文中首次提出的。他总结:控制的什么被反转了?就是:获得依赖对象的方式反转了。
AOP:可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善。OOP引入封装、继承和多态性等概念来建立一种对象层次结构,用以模拟公共行为的一个集合。当我们需要为分散的对象引入公共行为的时候,OOP则显得无能为力。也就是说,OOP允许你定义从上到下的关系,但并不适合定义从左到右的关系。例如日志功能。日志代码往往水平地散布在所有对象层次中,而与它所散布到的对象的核心功能毫无关系。对于其他类型的代码,如安全性、异常处理和透明的持续性也是如此。这种散布在各处的无关的代码被称为横切(cross-cutting)代码,在OOP设计中,它导致了大量代码的重复,而不利于各个模块的重用。
AOP的使用场景
Authentication 权限
Caching 缓存
Context passing 内容传递
Error handling 错误处理
Lazy loading 懒加载
Debugging 调试
logging, tracing, profiling and monitoring 记录跟踪 优化 校准
Performance optimization 性能优化
Persistence 持久化
Resource pooling 资源池
Synchronization 同步
Transactions 事务
AOP的使用
可以通过配置文件或者编程的方式来使用Spring AOP。
配置可以通过xml文件来进行,大概有四种方式:
1.配置ProxyFactoryBean,显式地设置advisors, advice, target等
<bean id="sayhelloadvice" class="test3.SayHelloBeforemale"/>
<bean id="target" class="test3.waiter"/>
<bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean"
p:proxyInterfaces="test3.wait"
p:interceptorNames="sayhelloadvice"
p:target-ref="target"
/>
2.配置AutoProxyCreator,这种方式下,还是如以前一样使用定义的bean,但是从容器中获得的其实已经是代理对象
3.通过aop:config来配置
4.通过<aop: aspectj-autoproxy>来配置,使用AspectJ的注解来标识通知及切入点
也可以直接使用ProxyFactory来以编程的方式使用Spring AOP,通过ProxyFactory提供的方法可以设置target对象, advisor等相关配置,最终通过 getProxy()方法来获取代理对象
APSECT全局日志
首先引入包
其次代码如下
@Aspect
@Component
public class WebLogAspect {
private final static Logger log = LoggerFactory.getLogger(WebLogAspect.class);
private Gson gson = new Gson();
//申明一个切点 里面是 execution表达式
@Pointcut("execution(public * com.bosssoft.hr.controller..*.*(..))")
private void controllerAspect(){}
//请求method前打印内容
@Before(value = "controllerAspect()")
public void methodBefore(JoinPoint joinPoint){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
//打印请求内容
log.info("===============请求内容===============");
log.info("请求地址:"+request.getRequestURL().toString());
log.info("请求方式:"+request.getMethod());
log.info("请求类方法:"+joinPoint.getSignature());
log.info("请求类方法参数:"+ Arrays.toString(joinPoint.getArgs()));
log.info("===============请求内容===============");
}
//在方法执行完结后打印返回内容
@AfterReturning(returning = "o",pointcut = "controllerAspect()")
public void methodAfterReturing(Object o ){
log.info("--------------返回内容----------------");
log.info("Response内容:"+gson.toJson(o));
log.info("--------------返回内容----------------");
}
}
全局异常
package com.bosssoft.hr.framework.exception;
import com.bosssoft.hr.framework.exception.business.BaseBusinessException;
import com.bosssoft.hr.utils.CommonConst;
import com.bosssoft.hr.vo.ResponseVO;
import com.bosssoft.hr.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.lang.reflect.UndeclaredThrowableException;
/**
* 全局异常捕获
*
* @author cws
* @title: WebExceptionAspect
* @package com.bosssoft.hr.framework.webaspect
* @date: 2019/3/21 11:14
**/
@Slf4j
@ControllerAdvice(basePackages="com.bosssoft.hr.controller")
public class WebExceptionAspect {
/**
* 全局捕获异常
*
* @author cws
* @date 2019/3/26 15:23
* @param e
* @return com.bosssoft.hr.vo.ResponseVO
**/
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseVO errorMsg(Throwable e){
e.printStackTrace(); // 打印异常栈
//shiro异常
if(e instanceof AuthenticationException){
AuthenticationException eauth = (AuthenticationException) e;
return ResultUtil.error(e.getMessage());
}
//自定义异常
if (e instanceof BaseBusinessException) {
BaseBusinessException ebase = (BaseBusinessException) e;
return ResultUtil.error((Integer.valueOf(ebase.getCode())),ebase.getMessage());
}
if (e instanceof UndeclaredThrowableException) {
e = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
}
ResponseStatus responseStatus = ResponseStatus.getResponseStatus(e.getMessage());
if (responseStatus != null) {
log.error(responseStatus.getMessage());
return ResultUtil.error(responseStatus.getCode(), responseStatus.getMessage());
}
//未知错误
return ResultUtil.error(CommonConst.DEFAULT_ERROR_CODE, ResponseStatus.ERROR.getMessage());
}
}