我同时使用Spring4
和Spring 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的新手,有人可以帮助我吗?
您的@ComponentScan
正在尝试解决并将依赖项自动关联到CoreController
。当它尝试解决依赖关系时,会在您的@Bean
类中找到Application
。然后,它尝试通过调用Application.commandService()
来解决此依赖性。调用此方法时,它将看到匹配的@Pointcut
并调用您的advice方法。由于您的@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;
}
}
您被使用过
joinPoint.proceed();
没有回报,只需将回报添加为
return joinPoint.proceed();