zoukankan      html  css  js  c++  java
  • 在静态方法中应用spring注入的类

    最近在一次项目的重构中,原项目需要在静态方法中调用service,现在需要更换框架,service需要自动注入,无法再静态方法中调用

    解决思路:

    创建一个当前类的静态变量,创建一个方法,使用@PostConstruct 进行注解,被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。方法中将当前service,调用时直接使用静态变量调用service

    代码实例:

        @Component
        public class AutoLoginUtil {
            @Autowired
            private IUserService userService;
    
            private static AutoLoginUtil autoLoginUtil;
    
            @PostConstruct
            public void init() {
                autoLoginUtil = this;
                autoLoginUtil.userService = this.userService;
            }
    
            public static void autoLogin() {
                autoLoginUtil.userService.queryUserAutoLogin();
            }
    
        }
  • 相关阅读:
    进程和线程
    关于offer对比
    CVTE面经
    重定向
    奇虎360面试经验
    百纳信息(海豚浏览器)面经
    携程网面经
    百度面经
    位运算
    Cracking the Coding Interview 4.8
  • 原文地址:https://www.cnblogs.com/jiangwz/p/9447773.html
Copyright © 2011-2022 走看看