spring 基础

139 阅读2分钟

IOC 本质

image.png

xml配置bean

image.png

获取ApplicaitonContext (xml获取)

image.png

ioc创建对象的方式(在加载配置文件时bean已经被创建)

image.png

image.png

spring配置

alias别名

image.png

id,class,name

image.png

import

image.png

DI依赖注入

构造器注入 跟上面一样

setter注入

多种类型注入

image.png

image.png

p命名,c命名注入

image.png

bean装配的三种方式

image.png

xml 显示的装配(上面就是,在xml中不使用autowire)

自动装配(1.在xml中使用autowire通过byname或者Bytype 2.注解)

1.在xml中使用autowire通过byname或者Bytype

image.png

image.png ps:people有三个属性,name,dog,cat

image.png

注解自动装配(这里还没使用@bean,还是在xml配置bean,只是使用了@AUTOWIRE)

前提

image.png

@Autowired,@Qualifier连用 可以在有多个类型相同的时候根据bean的名字注入 image.png

@Resource

完全Java配置 不需要xml

image.png

image.png

代理模式

静态代理

代码步骤

image.png

3.代理角色

image.png

image.png

好处

image.png

动态代理

c95ff29ce52bb2723157ac18598bf30.png

AOP

xml配置实现

前置方法,后置方法等写一个类实现各自的接口,如加入前置日志

image.png 然后在xml配置

image.png

xml配置实现(与上面不同的是只需要定义一个切面类然后在xml指定相应的前置,后置方法)

image.png

注解实现(推荐 最简单)

//增强的类 @Component @Aspect //生成代理对象 @Order(3) public class UserProxy {

//相同切入点抽取
@Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void pointdemo() {

}

//前置通知
//@Before注解表示作为前置通知
@Before(value = "pointdemo()")
public void before() {
    System.out.println("before.........");
}

//后置通知(返回通知)
@AfterReturning(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void afterReturning() {
    System.out.println("afterReturning.........");
}

//最终通知
@After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void after() {
    System.out.println("after.........");
}

//异常通知
@AfterThrowing(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void afterThrowing() {
    System.out.println("afterThrowing.........");
}

//环绕通知
@Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    System.out.println("环绕之前.........");

    //被增强的方法执行
    proceedingJoinPoint.proceed();

    System.out.println("环绕之后.........");
}

}

  • proceedingJoinPoint.proceed();执行被增强的方法,通常是放在@Around,主要是前后执行
  • after是方法之后执行,有没有异常都执行
  • AfterThrowing是返回值之后执行,有异常之后不执行