2012-11-29 90 views
-2

如何在java中配置基于注释的弹簧方面?如何在java中配置基于注释的弹簧方面

假设我们想拦截一个弹簧服务,我们通常通过AOP切入点表达来实现。这个例子详细说明了如何使用注解来代替表达式。这在我们使用注释时更加便于携带。

有很多例子,但很少有正确的内容。因此把它放在这里...

这是一个解决的问题。我在春天张贴我的答案,因此帮助别人包括我自己在内。基于

+0

更新与笔记的问题,它有助于澄清? – MountainRock

+0

你也应该接受你的答案,以便其他人可以看到它。 – kazanaki

回答

0

注释AOP通知

1.定义注释

public @interface ApplyAuthorisationAdvice { 
} 

春天配置文件设置<aop:aspectj-autoproxy />如果

之前没有做过

2.

import org.aopalliance.aop.Advice; 
import org.aspectj.lang.annotation.Aspect; 

@Aspect 
@Component 
public class AuthorisationAspect implements Advice { 

    private final static Logger logger = Logger.getLogger(AuthorisationAspect.class); 

    @Autowired 
    MyService myService; 

    @SuppressWarnings("unchecked") 
    @AfterReturning(pointcut = "@annotation(com.example.ApplyAuthorisationAdvice)", returning = "result") 
    public void afterReturning(JoinPoint joinPoint, Object result) { 

     if (result != null && (result instanceof List)) { 
      // filter stuff 
     } 

    } 
} 

3.A在服务pply注释需要被截获

@Component("myService") 
public class MyServiceImpl implements MyService { 
    @ApplyAuthorisationAdvice 
    public List<MySummary> search(MyContext searchContext) { 
    } 
}