Domanda

I try to make a pointcut, to log the SQL queries

  @Before("execution(* org.springframework.jdbc.core.JdbcTemplate.*(String, ..))")
public void logSQLQueries() {
        System.out.println("@@");
    }

I am trying to implement the code as here; http://www.gotoquiz.com/web-coding/programming/java-programming/log-sql-statements-with-parameter-values-filled-in-spring-jdbc/

but I get

java.lang.IllegalArgumentException: Can not set org.springframework.jdbc.core.JdbcTemplate field com.xyz.abc.dao.ABCDaoImpl.jdbcTemplate to com.sun.proxy.$Proxy53

I have created the jdbcTemplate bean in my *-servlet.xml and have autowired this in all my DAO's. Works perfectly fine but adding the pointcut gives the exception. Any ideas ??

È stato utile?

Soluzione

Spring, by default, uses JDK Dynamic proxies to apply AOP. (For more information on proxies see here).

What happens isthat a dynamic class is created (com.sun.proxy.$Proxy53) which implements all the interfaces that the target class implements. For a JdbcTemplate that is JdbcOperations and InitializingBean. So the dynamic class is a JdbcOperations but not a JdbcTemplate and hence the injection fails.

You have a couple of solutions

  1. Use the interface JdbcOperations instead of the class JdbcTemplate to program against
  2. Use class based proxies
  3. Use loadtime weaving

Now option 1 and 2 are the easiest whereas option 3 is the most powerful and complex to get started (see the links below).

For 1 in your class change

@Autowired
private JdbcTemplate jdbcTemplate;

To

@Autowired
private JdbcOperations jdbcTemplate; 

If you are extending JdbcDaoSupport you might be in a pickle and then it won't work.

Option 2, assuming you have <aop:aspectj-autoproxy /> set the proxy-target-class attribute to true. This will require cglib and will create class based proxies instead of interface based proxies.

For option 3 I refer to the reference guide as that involves (probably) a java-agent and might be a little more complicated to get working.

Links

  1. Understanding AOP proxies
  2. Load-time weaving with AspectJ
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top