Spring AOP 不工作

Spring AOP is not working

我是 spring aop 的新手。我有以下 classes。 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。看点Class @方面 public class TimeAOP { 长启动时间 = 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.配置Class

@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.测试 Class

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:启动日期 [2016 年 3 月 6 日星期日 12:27:05 EST];上下文层次的根 汇款前 帐户 1 余额:10.0 帐户 2 余额:20.0 汇款后 帐户 1 余额:5.0 账户2余额:25.0

AOP 永远不会执行。谁能帮帮我??

由于您没有使用 XML,您需要 return 来自 @Configuration

的 Aspect bean
@Bean
public TimeAOP timeAspect() {
    return new TimeAOP();
}