我是新來的春天aop。我有以下課程。 1.接口春季AOP不能正常工作
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 公共類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.配置類
@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.spring[email protected]5d099f62:啓動日期[太陽Mar 06 12:27:05 EST 2016];上下文結構 根匯款 賬戶餘額1之前:10.0 賬戶餘額2:20.0 匯款 賬戶餘額1後:5.0 賬戶餘額2:25.0
的AOP是永遠不會執行。任何人都可以幫助我?
是您的方面類是一個Spring bean(有@Component註釋)? –
不,Aspect類不是一個spring bean,是否需要將它作爲一個bean? –
是的,請參閱第10.2.2節(http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/aop.html) –