• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

同一个类中调用Java注解方法生效

开发技术 开发技术 2周前 (04-07) 4次浏览

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

方法二:从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)

程序员灯塔
转载请注明原文链接:同一个类中调用Java注解方法生效
喜欢 (0)