1.IOC中
1.@Configuration :
作用:表明当前类是一个配置类
属性:
value:它和basePackages的作用是一样的,
都是指定创建容器时要扫描的包
细节:当配置类作为AnnotationConfigApplicationContext
对象创建的参数时,该注解可以不写。
2.@ComponentScan:
作用:扫描包,里边的value属性为我们要扫描的包名;
3.@Bean
作用:用于把当前方法的返回值作为bean对象存入spring的IOC容器中
属性:
name:用于指定bean的id。默认值是当前方法的名称
细节:当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
查找的方式和Autowired注解的作用是一样的。
4.@Import:
作用:用于导入其他的配置类
属性:
value:用于指定其他配置类的字节码
细节:当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类
5. @Propertysource :
作用:用于指定properties文件的位置
属性:
value:指定文件的名称和路径
关键字:classpath;表示类路径下
6.@Component
作用:用于把当前类存入spring容器中
属性:
value:用于指定bean的ID,当我们不写诗,它的默认值是当前类名,且类名首字母小写
@Controller:一般用在表现层
@Service:一般用于业务层
@Repository:一般用于持久层
以上三个注解作用和属性和Component是一样的,这三个是spring框架为我们提供明确的三层使用的注解。
7.@Autowired:
**作用:**自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功如果Ioc容器中没有任何bean的类型和要注入的变量类型匹配则报错,如果有Ioc容器中有多个类型匹配时,需要指明id使用,默认变量名。
出现位置:变量上,方法上
细节: 在使用注解注入时,set方法就不是必须了
@Qualifier :
作用:在按照类中注入的基础之上在按照名称注入。它在给类 但是在给方法参数注入时可以。(要结合autowired结合使用)
属性:
value:用于指定指定bean的id
**@Resource:**
作用:直接按照bean的id使用,可以直接独立使用。
属性:
name:用于指定bean的id。
以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。另外,集合类型的注入只能通过xml来实现。
**@Value:**
作用:用于注入基本类型和String类型的数据
属性:
value:用于指定数据的值,他可以使用spring中的Spel(也就是spring的EL表达式)
spel的写法:${表达式}
用于改变作用范围的:
作用集合在bean标签中使用scope属性实现的功能是一样的
**@Scope:**
作用:用于指定bean的作用范围
属性:
value:用于范围的取值。常用取值:singleton,prototype.
和生命周期相关的:(了解)
作用和在bean标签中使用init-method和destroy-method属性的作用是一样的
**@PreDestroy:**
作用:用于指定销毁方法
**@PostContext:**
作用:用于指定初始化方法。
2. AOP中
package com.itcast.util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
*
* 用于记录日志的工具类,他里面提供了公共的代码
*/
@Component("logger")
@Aspect //表示当前类是一个切面类
public class Logger {
@Pointcut("execution(* com.itcast.service.impl.*.*(..))")
private void pt1(){
}
/**
*
* 用于打印日志,计划让其在切入点方法执行之前执行(切入点方法也是业务层方法)
*/
/**
* 前置
*/
@Before("pt1()")
public void beforePrintLog(){
System.out.println("Logger类中的printLog方法开始记录日志了");
}
/**
* 后置通知
*/
@AfterReturning("pt1()")
public void afterReturningPrintLog(){
System.out.println("Logger类中的afterReturningPrintLog方法开始记录日志了");
}
/**
* 异常通知
*/
@AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("Logger类中的afterThrowingPrintLog方法开始记录日志了");
}
/**
*
* 最终通知
*/
@After("pt1()")
public void afterPrintLog(){
System.out.println("Logger类中的afterPrintLog方法开始记录日志了");
}
/**
* 环绕通知
*
* 当我们配置了环绕通知时,切入点方法没有执行,而通知方法执行了
*
* spring中的环绕通知
* 他是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方法
*/
@Around("pt1()")
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
Object[] args = pjp.getArgs();
System.out.println("前置通知");
rtValue = pjp.proceed(args);//明确调用业务层方法()切入点方法
System.out.println("后置通知");
return rtValue;
} catch (Throwable throwable) {
System.out.println("异常通知");
throwable.printStackTrace();
}finally{
System.out.println("最终通知");
}
return null;
}
}
来源:CSDN
作者:xupt_zy
链接:https://blog.csdn.net/weixin_45093436/article/details/104039420