• 在静态方法中应用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();
            }
    
        }
  • 相关阅读:
    js日期 操作
    c# 调用c++ dll
    多维数组与交错数组的转换
    c++多态
    c++ 指向类成员函数的函数指针
    c++虚析构函数的使用及其注意点
    c++模板实现 linq
    Php 常用类
    Php ORM 对象关系映射
    Php OpenID
  • 原文地址:https://www.cnblogs.com/jiangwz/p/9447773.html
Copyright © 2020-2023  润新知