Spring框架核心
IOC 控制反转
控制反转(IOC)是思想,依赖注入(DI)是实现技术。
Spring框架通过IOC容器来管理所有java对象的实例化和初始化,控制对象与对象之间的依赖关系。依赖注入分为Set注入、接口注入、注解注入、构造器注入。
IOC配置
1. 注解定义Spring中的bean(组件)
@Component,泛化概念,表示容器中的一个组件,可作用在Service等任何层次。
@Repository,作用于数据访问层Dao层。
@Service,作用于业务层Service层。
@Controller,作用于控制层Controller层
2. 注解实现依赖注入
@Autowired,默认按照Bean的类型自动装配,若要按照名称需使用@Qualifier配合。
@Resource,默认按照Bean的名称自动装配。
面向切面编程AOP
AOP,为目标对象生成一个代理对象,并在代理对象中实现对目标对象增强,采用动态代理模式为目标对象横向织入增强功能。
AOP术语
通知
前置通知(Before)、后置通知(AfterReturning)、环绕通知(Around)、异常通知(AfterThrowing)、最终通知(After)
AOP的配置方式(注解@Aspect)
1. Service层接口使用JDK动态代理
2. Controller层非接口使用Cglib动态代理:缺少一个接口类而已.。
public interface IJdkProxyService {
void code1();
String code2();
String code3() throws Exception;
}
@Service
public class JdkProxyDemoServiceImpl implements IJdkProxyService {
@Override
public void code1() {
System.out.println("JdkProxyServiceImpl.code1()");
}
@Override
public String code2() {
System.out.println("JdkProxyServiceImpl.code2()");
return "hello world";
}
@Override
public String code3() throws Exception {
System.out.println("JdkProxyServiceImpl.code3()");
throw new Exception("some exception");
}
}
package tech.springframework.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
@EnableAspectJAutoProxy
@Component
@Aspect
public class LogAspect {
// 定义切点
@Pointcut("execution(* tech.springframework.service.*.*(..))")
private void pointCutMethod() {
}
// 环绕通知
@Around("pointCutMethod()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("-----------------------");
System.out.println("环绕通知: 进入方法");
Object o = pjp.proceed();
System.out.println("环绕通知: 退出方法");
return o;
}
// 前置通知
@Before("pointCutMethod()")
public void doBefore() {
System.out.println("前置通知");
}
// 后置通知
@AfterReturning(pointcut = "pointCutMethod()", returning = "result")
public void doAfterReturning(String result) {
System.out.println("后置通知, 返回值: " + result);
}
// 异常通知
@AfterThrowing(pointcut = "pointCutMethod()", throwing = "e")
public void doAfterThrowing(Exception e) {
System.out.println("异常通知, 异常: " + e.getMessage());
}
// 最终通知
@After("pointCutMethod()")
public void doAfter() {
System.out.println("最终通知");
}
}
-----------------------------------------------------------------------------------------
环绕通知: 进入方法
前置通知
JdkProxyServiceImpl.code1()
最终通知
环绕通知: 退出方法
-----------------------
环绕通知: 进入方法
前置通知
JdkProxyServiceImpl.code2()
后置通知, 返回值: hello world
最终通知
环绕通知: 退出方法
-----------------------
环绕通知: 进入方法
前置通知
JdkProxyServiceImpl.code3()
异常通知, 异常: some exception
最终通知
SpringMVC