Spring 3.0 / AOP / Aspectj:autoproxy intercept any

2019-02-18 19:03发布

问题:

I'm trying to intercept any call to getConnection() method to setup the dbms indentifier . I've implemented an aspect to get it but I don't get anything. Any idea? Thanks!

import java.sql.CallableStatement;
import java.sql.Connection;

import javax.servlet.http.HttpSession;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import es.iberia.tryp.model.entities.Usuario;

@Component
@Aspect
public class ConnectionAspect {

    @AfterReturning(value = "execution(java.sql.Connection javax.sql.DataSource+.getConnection(..))", returning = "connection")
    //@AfterReturning(value = "execution(java.sql.Connection org.springframework.jdbc.datasource.*.*(*))", returning = "connection")
    //@AfterReturning(value = "execution(java.sql.Connection java.sql.Connection *(..))", returning = "connection")
    //@AfterReturning(value = "execution(java.sql.Connection org.springframework.jdbc.datasource.DriverManagerDataSource.*(..))", returning = "connection")

    public void prepare (Connection connection) throws Throwable {

        HttpSession httpSession = (HttpSession) RequestContextHolder.currentRequestAttributes().resolveReference(RequestAttributes.REFERENCE_SESSION);

        if (httpSession!=null && (Usuario)httpSession.getAttribute("usuario")!=null && ((String)((Usuario)httpSession.getAttribute("usuario")).getNomina())!=null) {
            String nomina = (String)((Usuario)httpSession.getAttribute("usuario")).getNomina();
            String prepSql = "{ call DBMS_SESSION.SET_IDENTIFIER('" + nomina +"') }";
            CallableStatement cs = connection.prepareCall(prepSql);                             
            cs.execute();
            cs.close();         
        }
    }
} 

回答1:

Yes, I have an idea: Actually your pointcuts match the desired calls, but they are in the java package which (like the javax package) is excluded from weaving by default.

There is a way to remove that restriction via command line and aop.xml, but please be aware of potential problems concerning classloading. You have to make sure the classloader loading the java classes has a weaver attached, so if you have the option not to use LTW, just weave the JDK class files and use those woven classes, and you will be fine. Otherwise you might have a "hen and egg" problem.



回答2:

Check whether you have added the below tag in your xml file.

aop:aspectj-autoproxy

Also check whether you have added the bean definition inside the xml for this ConnectionAspect class.