代码之家  ›  专栏  ›  技术社区  ›  kramsiv94

Spring boot AOP特性导致autwired bean返回null

  •  0
  • kramsiv94  · 技术社区  · 6 年前

    使用 @Around 定义方面的注释会导致bean的自动连接返回null。我知道aspectj可以通过一些代理来解决这个问题。我只是不知道这些注释是什么,也不知道应该放在哪里。这只发生在@Around方面,而不是@Before或@After方面。

    @SpringBootApplication
    public class AopStuffApplication implements CommandLineRunner{
    
        @Autowired
        private Business1 business1;
    
        private static final Logger LOGGER = Logger.getLogger(AopStuffApplication.class.getName());
    
        public AopStuffApplication() {}
    
        public static void main(String[] args) {
            SpringApplication.run(AopStuffApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            LOGGER.info(business1.calculateSomething());
        }
    }
    

    @Service
    public class Business1 {
    
        @Autowired
        private Dao1 dao1;
    
        public String calculateSomething() {
            return dao1.retrieveSomething();
        }
    }
    

    @Repository
    public class Dao1 {
    
        public String retrieveSomething() {
            System.out.println("Inside of retrieveSomething().");
            return "Dao1";
        }
    }
    

    @Aspect
    @Component
    public class MethodExecutionCalculationAspect {
    
        private static final Logger LOGGER = Logger.getLogger(MethodExecutionCalculationAspect.class.getName());
    
        @Around("execution(* com.training.AOPStuff.aopstuff.data.Dao1.retrieveSomething(..))")
        public void trackElapsedTime(ProceedingJoinPoint proceedingJoinPoint) {
    
            //start time
            long startTime = System.currentTimeMillis();
    
            //allow execution of method
            try {
                proceedingJoinPoint.proceed();
            } catch (Throwable e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            //end time
            long elapsedTime = System.currentTimeMillis() - startTime;
    
            System.out.println("message from within gthe aspect.");
    
            //LOGGER.info("Elapsed time for " + proceedingJoinPoint + " was " + elapsedTime);
    
        }
    
    }
    
    0 回复  |  直到 6 年前