我正在使用 Spring4
和 Spring Boot
。
在我厌倦使用 AOP 之前,我在 Controller 中使用的 Bean(CommandService) 可以很好地自动注入(inject),但是当我厌倦使用 AOP 收集一些调试消息之后,该 Bean 就变成了 null!
这是我的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 抛出空指针:
@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 新手,有人可以帮助我吗?
最佳答案
您的@ComponentScan
正在尝试解析您的依赖项并将其 Autowiring 到CoreController
中。当它尝试解决依赖关系时,它会在您的 Application
类中找到 @Bean
。然后,它尝试通过调用 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;
}
}
关于java - 使用AOP后注入(inject)的bean变为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26644657/