我是新来的。我有以下课程。 的 1。接口
public interface AccountService {
public void transferMoney(
long sourceAccountId, long targetAccountId, double amount);
public void depositMoney(long accountId, double amount) throws Exception;
public Account getAccount(long accountId);
}
2。 Aspect Class @方面 公共课TimeAOP { long startTime = 0;
@Pointcut("execution(* *.transferMoney(..))")// the pointcut expression
private void anyOldTransfer() {}// the pointcut signature
@After("anyOldTransfer()")
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
long elapsedTime = System.nanoTime() - startTime;
String className = target.getClass().getCanonicalName();
String methodName = method.getName();
System.out.println("Execution of " + className + "#" + methodName
+ " ended in " + new BigDecimal(elapsedTime).divide(
new BigDecimal(1000000)) + " milliseconds");
}
@Before("anyOldTransfer()")
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("Starting");
startTime = System.nanoTime();
}
}
3。配置类
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.xxx")
public class Ch2BeanConfiguration {
@Bean
public AccountService accountService() {
AccountServiceImpl bean = new AccountServiceImpl();
bean.setAccountDao(accountDao());
return bean;
}
@Bean
public AccountDao accountDao() {
AccountDaoInMemoryImpl bean = new AccountDaoInMemoryImpl();
//depedencies of accountDao bean will be injected here...
return bean;
}
}
4。测试类
public class Main {
public static void main(String[] args){
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(Ch2BeanConfiguration.class);
AccountService accountService = applicationContext.getBean("accountService",
AccountService.class);
System.out.println("Before money transfer");
System.out.println("Account 1 balance :" + accountService.getAccount(1).getBalance());
System.out.println("Account 2 balance :" + accountService.getAccount(2).getBalance());
accountService.transferMoney(1, 2, 5.0);
System.out.println("After money transfer");
System.out.println("Account 1 balance :" + accountService.getAccount(1).getBalance());
System.out.println("Account 2 balance :" + accountService.getAccount(2).getBalance());
}
}
输出: 2016年3月6日下午12:27:05 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh 信息:刷新org.springframework.context.annotation.AnnotationConfigApplicationContext@5d099f62:启动日期[Sun Mar 06 12:27:05 2016];上下文层次结构的根 汇款之前 账户1余额:10.0 账户2余额:20.0 汇款后 账户1余额:5.0 账户2余额:25.0
永远不会执行AOP。任何人都可以帮助我?
答案 0 :(得分:0)
由于您不使用XML,因此您需要从@Configuration返回Aspect bean
@Bean
public TimeAOP timeAspect() {
return new TimeAOP();
}