使用AOP后,注入的bean变为null

时间:2014-10-30 03:38:46

标签: java spring spring-mvc spring-boot spring-aop

我正在使用Spring4Spring Boot

在我厌倦使用AOP之前,我在控制器中使用的Bean(CommandService)是自动注入的,但是在我厌倦了使用AOP来收集一些调试消息之后,bean变为空了!

这是我的Application.java

@Configuration
@EnableAutoConfiguration
@ComponentScan({"hello","wodinow.weixin.jaskey"})
public class Application extends  {

public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(Application.class, args);

    LogUtil.info("Beans provided by Spring Boot:");
    String[] beanNames = ctx.getBeanDefinitionNames();
    Arrays.sort(beanNames);
    for (String beanName : beanNames) {
        LogUtil.info(beanName);
    }
    LogUtil.info("Application Boots completes!");
}

@Bean
public CommandService commandService(){
    LogUtil.debug("CommandService.getInstance()"+ CommandService.getInstance()) ;//here indeed I could see spring executes this and returns a object when application boots
    return CommandService.getInstance();//This returns a singleton instance
}

}

我的控制器抛出空指针:

@Controller
public class CoreController {

    @Autowired
    CommandService commandService;//here the service is null after using aop

    //...some request methods
}

我刚才添加的方面:

//if I comment out these two annoations, the bean will be auto injected well
@Aspect
@Component
public class LogAspect {
@Pointcut("execution(* wodinow.weixin.jaskey..*.*(..))")
    private void debug_log(){};

    @Around("debug_log()")
    public void debug(ProceedingJoinPoint joinPoint) throws Throwable{
        LogUtil.debug("enter "+joinPoint.getSignature());
        try{
           joinPoint.proceed();
           LogUtil.debug("returns from "+joinPoint.getSignature());
        }
        catch(Throwable t){
            LogUtil.error(t.getMessage()+"occurs in "+joinPoint.getSignature(),t);
            throw t;
        }
    }
}

我是Spring的新手,有人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

您的@ComponentScan正在尝试解析并将您的依赖关系自动装入CoreController。当它尝试解析依赖关系时,会在@Bean类中找到Application。然后,它会尝试通过调用Application.commandService()来解决此依赖关系。调用此方法时,它会看到匹配的@Pointcut并调用您的建议方法。由于您的@Advice没有返回任何内容,调用者也会看到没有返回任何内容,并且会说该依赖项的解析返回null

此处的修复只是更改您的@Around建议以返回您的调用值。

@Around("debug_log()")
public Object debug(ProceedingJoinPoint joinPoint) throws Throwable{
    LogUtil.debug("enter "+joinPoint.getSignature());
    try{
        // return the invocation
        return joinPoint.proceed();
    }
    catch(Throwable t){
        LogUtil.debug(t.getMessage()+"occurs in "+joinPoint.getSignature(),t);
        throw t;
    }
}

答案 1 :(得分:0)

您习惯了

joinPoint.proceed(); 

没有收益,只需将收益添加为

return joinPoint.proceed();