方法一:添加一个新的类,使用类之间调用,此时注解生效。

方法二:从ApplicationContext中获取该类的bean,然后调用带注解的方法。

@Component
public class SpringBootBeanUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringBootBeanUtil.applicationContext == null) {
            SpringBootBeanUtil.applicationContext = applicationContext;
        }
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
}

@Service
public class ExperimentLoader {

    @PostConstruct
    public void init() {
        SpringBootBeanUtil.getBean(ExperimentLoader.class).loadExperiments();
    }

    @Scheduled(cron = "0 0/30 * * * *")
    public void scheduledLoad() {
       SpringBootBeanUtil.getBean(ExperimentLoader.class).loadExperiments();
    }

    @Transactional
    public void loadExperiments() {
		//this is the method that need annotation
    }
}

方法三:引入本类的一个实例,调用时,使用实例调用。

@Service
public class ExperimentLoader {

    @Autowired
    private ExperimentLoader loader;

    @PostConstruct
    public void init() {
        loader.loadExperiments();
    }

    @Scheduled(cron = "0 0/30 * * * *")
    public void scheduledLoad() {
        loader.loadExperiments();
    }

    @Transactional
    public void loadExperiments() {
		//this is the method that need annotation
    }

}

方法四:强制使用代理。这个方法在网上很常见,但我本地测试失败。此处也记一下:
启动类中添加 @EnableAspectJAutoProxy(exposeProxy = true)
调用:

 @PostConstruct
 public void init() {
     ((ExperimentLoader) AopContext.currentProxy()).loadExperiments();
 }

报错:

Caused by: java.lang.IllegalStateException: Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.
	at org.springframework.aop.framework.AopContext.currentProxy(AopContext.java:69)
posted on 2021-04-08 06:49  漫夭  阅读(897)  评论(0编辑  收藏  举报