看代码
package learning.aop2; import org.springframework.stereotype.Component; import java.sql.SQLException; @Component public class UserDAO { public void getAddUser(String name) throws SQLException { ConnMariaDB.getConn().createStatement(). execute("insert into user(name) VALUE (‘" + name + "‘)"); } }
得到连接
package learning.aop2; import java.sql.Connection; public class ConnMariaDB { public static ThreadLocal<Connection> threadLocal = null; public static Connection getConn() { return threadLocal.get(); } }
调用方法前往当前线程注入一个连接再调用
package learning.aop2; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @Component @Aspect public class JDBCAdvice { @Around("execution(* learning.aop2.UserDAO.*(..))") public Object wrapDAO(ProceedingJoinPoint joinPoint) throws Throwable { Connection conn = null; try { Class.forName("org.mariadb.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/user", "root", "dz520123"); conn.setAutoCommit(false); ConnMariaDB.threadLocal = new ThreadLocal<Connection>(); ConnMariaDB.threadLocal.set(conn); Object proceed = joinPoint.proceed(); conn.commit(); return proceed; } catch (Throwable throwable) { if (conn != null) { try { conn.rollback(); } catch (SQLException e) { } } throwable.printStackTrace(); throw throwable; } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } } }
扫描包
package learning.aop2; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @ComponentScan(basePackages = "learning.aop2") @EnableAspectJAutoProxy public class SpringConfig { }
测试.java
package learning.aop2; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.sql.SQLException; public class Main { public static void main(String[] args) throws SQLException { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class); UserDAO bean = applicationContext.getBean(UserDAO.class); bean.getAddUser("nihao"); } }
原文地址:https://www.cnblogs.com/dzcici/p/10142989.html
时间: 2024-11-06 23:40:39