zoukankan      html  css  js  c++  java
  • 同一个类中调用Java注解方法生效

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

    方法二:从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)
    
  • 相关阅读:
    通达OA二次开发
    通达OA 工作流程 表单设计 高级应用
    PLSQL Develop PlugIn 之脚本自动匹配补全工具CnPlugin
    Oracle性能优化之SQL语句
    Linux重置root密码步骤
    ORA-03113:通信通道的文件结尾解决
    Bat脚本实现MySQL数据库SQL文件备份
    访问父级组件实例
    访问根实例
    插槽其它示例
  • 原文地址:https://www.cnblogs.com/shoren/p/14630456.html
Copyright © 2011-2022 走看看