spring第5天(注解)

使用注解实现自动装配

注解
@Component:通用注解
@Repository:针对dao层注解
@Service:针对service层注解
@Controller:针对控制层的注解,(Servlet层)
以上四个注解的用途都是一样的(可以通用),但是实际开发中,会给不同的层使用不同的注解,都是创建对象
@Autowired:通过变量的类型自动取找对象,会自动扫描指定的包,然后去找和该属性类型相匹配的Bean组件(对象),等同于bean标签里面的property标签
@Qualifier("userDao") //配合@Autowired使用,指定装填的对象名
@Resource:可以通过属性的类型去找相关的对象,如果没找到,则会通过属性名称去匹配
@Autowired是Spring中的注解,@Resource是JDK中的

  1. 配置文件中需要添加关于context的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:p="http://www.springframework.org/schema/p" 
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
  1. 开启自动扫描:扫描类上面的注解
    base-package属性:要扫描的包名,多个包使用逗号隔开
<context:component-scan base-package="dao,service"/>
  1. 在需要创建对象的类
@Component("userDao")
  1. 增强方法也可以使用注解
    使用Pointcut设置一个签名,即将方法路径封装一下,下面的方法就可以使用签名的注解
@Pointcut("execution(* service..*.*(..))")
	public void pointcut() {
	}

前置增强:@Before("Pointcut")
后置增强:@AfterReturning(pointcut="Pointcut",returning = "result")
异常增强:@AfterThrowing(pointcut = "Pointcut",throwing = "e")

@Aspect
public class UserAop {
	private static final Logger log = Logger.getLogger(UserAop.class);

	/**
	 * 将execution(* service..*.*(..))做成一个签名,也就相当于该方法代表了某个切入点,
	 */
	@Pointcut("execution(* service..*.*(..))")
	public void pointcut() {

	}

	// 前置增强
	@Before("Pointcut")
	public void before(JoinPoint jp) {
		System.out.println("正在调用" + jp.getSignature().getName() + ",参数是" + Arrays.toString(jp.getArgs()));
	}

	// 后置增强
	@AfterReturning(pointcut="Pointcut",returning = "result")
	public void after(JoinPoint jp,Object result) {
		System.out.println("正在调用" + jp.getSignature().getName() + ",参数是" + Arrays.toString(jp.getArgs())+",返回值是"+result);
	}
	
	// 异常增强
		@AfterThrowing(pointcut = "Pointcut",throwing = "e")
		public void afterThrowing(JoinPoint jp,Throwable e) {
			System.out.println("正在调用" + jp.getSignature().getName() + ",参数是" + Arrays.toString(jp.getArgs())+"抛出的异常是"+e);
		}
}
posted @   不再犹豫27  阅读(15)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示