方法一:添加一個新的類,使用類之間調用,此時注解生效。
方法二:從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)