Spring Boot AOP方面导致自动连接的bean返回null

时间:2018-08-05 08:00:40

标签: java spring-boot aop autowired

使用@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 个答案:

没有答案