1注解初步
1、application.xml中开启扫描器
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName">
<!--开启扫描器 扫描加了注解的包--->
<context:component-scan base-package="dao.entity"></context:component-scan>
扫描多个包,每个包用逗号分隔
<context:component-scan base-package="dao.entity,xxxx.xxx,demo1.demo2,"></context:component-scan>
2、在类前加@Component("id名")注解
package dao.entity;
import org.springframework.stereotype.Component;
/**
* @Component("studentdao")相当于
* <bean id="studentdao" class="dao.entity.serviceImpl">
*/
@Component("studentdao")
public class serviceImpl {
public void fun(){
System.out.println("zengjia ...............");
}
}
@Component("id名")注解细化
该类是DAO层用 @Repository
该类是Service层 @Service
该类是控制器层 @Controller
2 注解声明事务
3 AOP面向切面编程
1、声明一个切入点,2、执行切面(某个函数)3、通知
普通类变为某个“通知”,实现接口:
a、前置通知
i 需要 aopaliance.jar , aspectjweaver.jar包
ii 配置
<!-- 配置前置通知-->
<!-- 前置通知类-->
<bean id="Logbefore" class="com.demo.aop.LogBefore">
</bean>
<!-- 方法所在类和通知进行关联-->
<aop:config>
<!-- 配置切入点(在哪里执行通知) execution-->
<aop:pointcut id="pointcut" expression="execution(public void dao.entity.serviceImpl.add()) or execution(public void dao.entity.serviceImpl.delete())"/>
<!--连接线 pointcut-ref -->
<aop:advisor advice-ref="Logbefore" pointcut-ref="pointcut"/>
<!-- execution (add()) ---pointcut-ref---- advice-ref( logbefor) -->
</aop:config>
iii 编写
实现 MethodBeforeAdvice 这个接口,重写 before(。。。)方法
package com.demo.aop;
import org.aspectj.lang.annotation.Before;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
//普通类变为 前置通知 实现一个接口
public class LogBefore implements MethodBeforeAdvice {
//前置通知的具体内容
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("前置通知。。。。。。。");
}
}
每当执行add()方法之前 自动执行的一个方法log()
add():业务方法
before():自动执行的方法,aop的前置通知
b、后置通知
实现 AfterReturningAdvice 接口,重写 afterReturning()方法