【问题标题】:Spring AOP is not injecting all the aspectsSpring AOP 没有注入所有方面
【发布时间】:2015-06-06 22:54:42
【问题描述】:

我正在尝试设置 Spring AOP 以将一些日志记录方法注入我的业务逻辑。 但只执行第一个方面(uiStarted)。以下所有(例如 uicreateMovie)都不是。第二个针对同一类中的类似方法。

LoggingBean

@Aspect
@Component
public class LoggingBean {
    private final Logger mLogger = Logger.getLogger(LoggingBean.class);

    //This one works
    @Before("execution(* de.rocketscienceengineering.springexampleproject.view.UI.startTheEngines(..))")
    public void uiStarted(JoinPoint joinp) {
    mLogger.info("Spring Log: the program started.");
    }

    //This one does not work
    @Before("execution(* de.rocketscienceengineering.springexampleproject.view.UI.createMovie(..))")
    public void uicreateMovie(JoinPoint joinp) {
    mLogger.info("Spring Log: trying to create movie.");
    }
}

LoggingBean https://github.com/tkupek/SpringExampleProject/blob/master/src/main/java/de/rocketscienceengineering/springexampleproject/util/LoggingBean.java

用户界面 https://github.com/tkupek/SpringExampleProject/blob/master/src/main/java/de/rocketscienceengineering/springexampleproject/view/UI.java

-- 更新

我现在更改了代码并实现了切入点。使用此代码

@Pointcut("execution(public * startTheEngines(..))")
public void startTheEngines() {

@Before("de.rocketscienceengineering.springexampleproject.view.UI.startTheEngines()")
public void uiStarted(JoinPoint joinp) {
    mLogger.error(">>>>>>>> Spring Log: before public methods");
}

我得到了正确的日志!

但如果我现在实现第二种方法,而不触及第一种方法

@Pointcut("execution(public * test(..))")
public void test() {
    startTheEngines();
}

@Pointcut("execution(public * startTheEngines(..))")
public void startTheEngines() {

@Before("de.rocketscienceengineering.springexampleproject.view.UI.startTheEngines()")
public void uiStarted(JoinPoint joinp) {
    mLogger.error(">>>>>>>> Spring Log: before public methods");
}

@Before("de.rocketscienceengineering.springexampleproject.view.UI.test())")
public void uiStartedtest(JoinPoint joinp) {
    mLogger.error("<<<<<<<< Spring Log: second log");
}

它只记录第二个日志而忘记了第一个。为什么?

【问题讨论】:

  • 主要区别在于startTheEngines() (public) 和createMovie() (private) 的可见性。您必须将 createMovie() 定义为 public 才能以这种方式使用 AOP。另见stackoverflow.com/questions/4402009/…
  • 这似乎是正确的,但即使我将可见性更改为公开它也不会拦截。

标签: java spring aop spring-aop


【解决方案1】:

Spring AOP 为您的 bean 创建一个代理并注入该代理。这意味着它仅适用于从该 bean 外部调用的方法(因为它必须通过该代理调用!)。

如果您需要它适用于任何方法,请尝试 AspectJ。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多