1. 程式人生 > >使用AOP思想封裝JDBC

使用AOP思想封裝JDBC

看程式碼

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");
    }
}