先来aop代码:
package com.aop;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class TestAopMethod {
// 定义一个切入点,通常是一个空的方法
@Pointcut("execution(* com.bean.User.*(..))")
public void select() {
}
// 前置通知
@Before("select()")
public void before() {
System.out.println("before");
}
// 后置通知
@After("select()")
public void after() {
System.out.println("after");
}
// 方法返回后通知
@AfterReturning("select()")
public void afterReturn() {
System.out.println("afterReturn ");
}
/*
* 环绕通知, 在此处发现一个问题,当around开启,before将不被执行、目前还未解决、先提出来
*/
@Around("select()")
public void around() {
System.out.println("around ");
}
}
jdbctemplate代码和AOP测试运行代码
package com.dao;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import com.bean.User;
import com.bean.UserMapper;
public class TestJdbc {
@Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
DataSource dataSource = (DataSource) ac.getBean("dataSource");
TestJdbc t = new TestJdbc();
t.setDataSource(dataSource);
t.select();
t.update();
User user = (User) ac.getBean("user");
System.out.println(user.getUsername());
System.out.println("-------------------------");
System.out.println(user.getPassword());
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public void select() {
String sql = "select * from user";
List<User> query = jdbcTemplate.query(sql, new UserMapper());
for (User user : query) {
System.out.println(user);
}
}
public void update() {
String sql = "update user set salary=? where id=?";
int update = jdbcTemplate.update(sql, 6666, 3);
System.out.println(update);
}
}
xml下的配置AOP
<aop:config>
<aop:aspect id="testMethod" ref="test">
<aop:pointcut expression="execution(* com.bean.User.getUsername(..))" id="selectAll"/>
<aop:after method="after" pointcut-ref="selectAll"/>
<aop:before method="before" pointcut-ref="selectAll"/>
<aop:after-returning method="afterReturn" pointcut-ref="selectAll"/>
<aop:around method="around" pointcut-ref="selectAll"/>
</aop:aspect>
</aop:config>
<bean id="test" class="com.aop.TestAopMethod"></bean>