1.AOP
(1)面向切面编程(方面),利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得
业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
(2)通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
(3)使用登录例子说明 AOP
2.AOP底层使用动态代理
2.1使用 JDK 动态代理
先附上代码框架
(1)创建接口,定义方法
public interface UserDao {
public int add(int a,int b);
public String update(String id);
}
(2)创建接口实现类,实现方法
public class UserDaoImpl implements UserDao {
@Override
public int add(int a, int b) {
return a+b;
}
@Override
public String update(String id) {
return id;
} }
(3)使用 Proxy 类创建接口代理对象
public class JDKProxy {
public static void main(String[] args) {
//创建接口实现代理对象
Class[] interfaces = {UserDao.class};
//Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// return null;
// }
//});
UserDaoImpl userDao =new UserDaoImpl();
UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
int result = dao.add(1,2);
System.out.println("result:"+result);
}
}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler{
//1.被代理类作为属性传过来
//有参构造传递
private Object obj;
public UserDaoProxy(Object obj){
this.obj=obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法之前
System.out.println("方法之前执行。。"+method.getName()+"传递的参数..."+ Arrays.toString(args));
//被增强的方法执行
Object res =method.invoke(obj,args);
//方法之后
System.out.println("方法之后执行.."+obj);
return res;
}
}
结果
3.AOP术语
连接点 :类里面哪些方法可以被增强这些方法成为连接点
切入点:实际真正被增强的方法,称为切入点
通知(增强):实际增强的逻辑部分成为通知(增强)
通知的多种类型:前置通知,后置通知,环绕通知,异常通知,最终通知
切面:把通知应用到切入点的过程
4.AOP操作
4.1 Spring 框架一般都是基于 AspectJ 实现 AOP 操作
AspectJ 不是 Spring 组成部分,独立 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使用,进行 AOP 操作
4.2 切入点表达式
切入点表达式作用:知道对哪个类里面的哪个方法进行增强
语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]
([参数列表]) )
举例 1:对 com.atguigu.dao.BookDao 类里面的 add 进行增强
execution(* com.atguigu.dao.BookDao.add(…))
举例 2:对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强
execution(* com.atguigu.dao.BookDao.* (…))
举例 3:对 com.atguigu.dao 包里面所有类,类里面所有方法进行增强
execution(* com.atguigu.dao.. (…))
4.3 AOP 操作(AspectJ 注解)
创建类,在类里面定义方法
//被增强类
public class User {
public void add(){
// int i=10/0;
System.out.println("add....");
}
}
2、创建增强类(编写增强逻辑)
在增强类里面,创建方法,让不同方法代表不同通知类型
//增强的类
public class UserProxy {
public void before() {//前置通知
System.out.println("before......");
} }
3.在 spring 配置文件中,开启注解扫描
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启注解扫描-->
<context:component-scan base-package="com.atguigu.spring5.aopano"></context:component-scan>
4.使用注解创建对象
@Component
public class User {
public void add(){
// int i=10/0;
System.out.println("add....");
}
}
//增强的类
@Component
public class UserProxy {
public void before() {//前置通知
System.out.println("before......");
} }
5.在增强类上面添加注解 @Aspect 表示生成代理对象
@Component
@Aspect
public class UserProxy {
public void before() {//前置通知
System.out.println("before......");
} }
6.在 spring 配置文件中开启生成代理对象 (bean1.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启注解扫描-->
<context:component-scan base-package="com.atguigu.spring5.aopano"></context:component-scan>
<!--开启Aspect生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
7.在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置
@Component
@Aspect //生成代理对象
public class UserProxy {
//前置通知
@Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void before(){
System.out.println("before....");
}
}
8.测试类(之后测试类不会进行改变)
@Test
public void testAopAno(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
User user =context.getBean("user",User.class);
user.add();
}
测试前置通知
9.五种通知
//增强类
@Component
@Aspect //生成代理对象
public class UserProxy {
//前置通知
@Before (value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void before(){
System.out.println("before....");
}
//方法执行之后 有无异常都返回
@After(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void after(){
System.out.println("after........");
}
//后置通知(返回通知)
@AfterReturning(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void afterReturning() {
System.out.println("afterReturning.........");
}
//异常通知
@AfterThrowing(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void AfterThrowing(){
System.out.println("afterThrowing........");
}
//环绕通知
@Around(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕之前........");
//被增强的方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后........");
}
}
测试
after 在方法执行之后执行 (不管有无异常都通知)
afterReturning 在返回值之后执行
此时将User类中的异常打开执行后
10.公共切入点抽取
在前置通知中直接使用表达式
//相同切入点抽取
@Pointcut(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void pointdemo(){
}
//前置通知
@Before(value = "pointdemo()")
//@Before (value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void before(){
System.out.println("before....");
}
11.有多个增强类多同一个方法进行增强,设置增强类优先级
在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高
新建一个增强类设置优先级(此处附上两个增强类全部代码)
@Component
@Aspect
@Order(1)
public class PersonProxy {
//
@Before(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void afterReturning() {
System.out.println("Person Before .........");
}
}
//增强类
@Component
@Aspect //生成代理对象
@Order(3)
public class UserProxy {
//相同切入点抽取
@Pointcut(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void pointdemo(){
}
//前置通知
@Before(value = "pointdemo()")
//@Before (value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void before(){
System.out.println("before....");
}
//方法执行之后 有无异常都返回
@After(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void after(){
System.out.println("after........");
}
//后置通知(返回通知)
@AfterReturning(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void afterReturning() {
System.out.println("afterReturning.........");
}
//异常通知
@AfterThrowing(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void AfterThrowing(){
System.out.println("afterThrowing........");
}
//环绕通知
@Around(value = "execution(* com.atguigu.spring5.aopano.User.add(..))")
public void Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕之前........");
//被增强的方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后........");
}
}
测试
4.4AOP 操作(AspectJ 配置文件方式)(前置通知为例)
1.创建两个类,增强类和被增强类,创建方法
public class BookProxy {
public void before(){
System.out.println("before......");
}
}
public class Book {
public void buy(){
System.out.println("buy...........");
}
}
2.写配置文件(全部代码)
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 创建两个类的对象-->
<bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean>
<bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean>
<!--配置aop增强-->
<aop:config>
<!-- 切入点-->
<aop:pointcut id="p" expression="execution(* com.atguigu.spring5.aopxml.Book.buy(..))"/>
<!--配置切面-->
<aop:aspect ref="bookProxy">
<!-- 配置增强作用在具体方法上-->
<aop:before method="before" pointcut-ref="p"/>
</aop:aspect>
</aop:config>
</beans>
3.测试
@Test
public void testAopXml(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
Book book =context.getBean("book",Book.class);
book.buy();
}
结果
4.5全注解方式
配置类
@Configuration
@ComponentScan(basePackages = {"com.atguigu"} ) // 开启组件扫描
@EnableAspectJAutoProxy(proxyTargetClass = true) //替代生成代理对象,不写默认值为false,写了默认值为true,可以不写这个注解
public class ConfigAop {
}
测试类
@Test
public void testAopXml1(){
ApplicationContext context =new AnnotationConfigApplicationContext(ConfigAop.class);
User user =context.getBean("user",User.class);
user.add();
}
测试
5.JdbcTemplate
代码框架
数据库 t_user
Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作
jdbc.properties
prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/tb2
prop.userName=root
prop.password=12345678
配置文件(bean.xml全部代码)
配置 JdbcTemplate 对象,注入 DataSource
创建 service 类,创建 dao 类,在 dao 注入 jdbcTemplate 对象
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 引入外部属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 组件扫描-->
<context:component-scan base-package="com.atguigu"></context:component-scan>
<!-- 配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${prop.driverClass}"></property>
<property name="url"
value="${prop.url}"></property>
<property name="username" value="${prop.userName}"></property>
<property name="password" value="${prop.password}"></property>
</bean>
<!-- JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
service
@Service
public class BookService {
//注入 dao
@Autowired
private BookDao bookDao; }
Dao
@Repository
public class BookDaoImpl implements BookDao {
//注入 JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate; }
创建实体类
public class Book {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
private String id;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Book{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
BookDao
public interface BookDao {
void add(Book book);
void updateBook(Book book);
void delete(String id);
int selectCount();
Book findBookInfo(String id);
List<Book> findAllBook();
void batchAddBook(List<Object[]> batchArgs);
void batchUpdateBook(List<Object[]> batchArgs);
void batchDeleteBook(List<Object[]> batchArgs);
}
BookDaoImpl
@Repository
public class BookDaoImpl implements BookDao {
//注入jdbctemplate
@Autowired
private JdbcTemplate jdbcTemplate;
//添加的方法
@Override
public void add(Book book) {
//创建sql
String sql ="insert into t_user values(?,?,?)";
//调用方法实现,
Object[] args ={book.getId(),book.getUsername(),book.getPassword()};
int update = jdbcTemplate.update(sql,args);
System.out.println(update);
}
@Override
public void updateBook(Book book) {
String sql ="update t_user set username=?,password=? where id=?";
Object[] args ={book.getUsername(),book.getPassword(),book.getId()};
int update = jdbcTemplate.update(sql,args);
System.out.println(update);
}
@Override
public void delete(String id) {
String sql ="delete from t_user where id=?";
int update = jdbcTemplate.update(sql,id);
System.out.println(update);
}
//查询表中的记录数
@Override
public int selectCount() {
String sql ="select count(*) from t_user";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
@Override
public Book findBookInfo(String id) {
String sql ="select * from t_user where id=?";
//调用方法
Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
return book;
}
//查询返回集合
@Override
public List<Book> findAllBook() {
String sql="select * from t_user";
List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
return bookList;
}
@Override
public void batchAddBook(List<Object[]> batchArgs) {
String sql =" insert into t_user values(?,?,?)";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
@Override
public void batchUpdateBook(List<Object[]> batchArgs) {
String sql = "update t_user set username=?,password=? where id=?";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
@Override
public void batchDeleteBook(List<Object[]> batchArgs) {
String sql ="delete from t_user where id=?";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
}
BookService
@Service
public class BookService {
//注入dao
@Autowired
private BookDao bookDao;
//添加的方法
public void addUser(Book book){
bookDao.add(book);
}
//修改
public void updateBook(Book book){
bookDao.updateBook(book);
}
//删除
public void delete(String id){
bookDao.delete(id);
}
//查询
public int findCount(){
return bookDao.selectCount();
}
//查询
public Book findOne(String id){
return bookDao.findBookInfo(id);
}
//返回查询集合
public List<Book> findAll(){
return bookDao.findAllBook();
}
//批量添加
public void batchAdd(List<Object[]> batchArgs){
bookDao.batchAddBook(batchArgs);
}
//批量修改
public void batchUpdate(List<Object[]> batchArgs){
bookDao.batchUpdateBook(batchArgs);
}
//批量删除
public void batchDelete(List<Object[]> batchArgs){
bookDao.batchDeleteBook(batchArgs);
}
}
测试类(不附截图)
@Test
public void testJdbcTemplate(){
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
//添加
Book book =new Book();
book.setUsername("angsa");
book.setPassword("123456");
bookService.addUser(book);
}
}
@Test
public void testJdbcTemplate(){
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
//修改
Book book =new Book();
book.setUsername("angsa");
book.setPassword("123456");
book.setId("1");
bookService.updateBook(book);
}
}
@Test
public void testJdbcTemplate(){
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
// 删除
bookService.delete("1");
}
}
@Test
public void testJdbcTemplate() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
// //批量添加
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"8", "www", "22"};
Object[] o2 = {"9", "www", "22"};
batchArgs.add(o1);
batchArgs.add(o2);
//调用批量添加
bookService.batchAdd(batchArgs);
}
}
@Test
public void testJdbcTemplate() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
//批量修改
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"wwwww", "22", "8"};
Object[] o2 = {"www111", "22", "9",};
batchArgs.add(o1);
batchArgs.add(o2);
//调用批量修改
bookService.batchUpdate(batchArgs);
}
}
@Test
public void testJdbcTemplate() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
// 批量删除
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1={"8"};
Object[] o2={"9",};
batchArgs.add(o1);
batchArgs.add(o2);
//调用批量删除
bookService.batchDelete(batchArgs);
}
}