在静态方法中调用Spring注入的类的方法

在静态方法中调用Spring注入的类的方法,第1张

静态方法中调用Spring注入的类的方法

在静态方法中调用Spring注入的类的方法

@Component
public class FileUtil {
    @Autowired
    FileConfig fileConfig;

    @Autowired
    private static FileConfig staticFileConfig;

    @PostConstruct
    public void init(){
        staticFileConfig = fileConfig;
    }

    public static void test(){
        String path = staticFileConfig.getPath();//getPath()是FileConfig中的方法
    }
}

@PostConstruct 该注解被用来修饰一个非静态的 void() 方法。被 @PostConstruct 修饰的方法会在服务器加载 Servlet 的时候运行,并且只会被服务器执行一次。PostConstruct 在构造函数之后执行,init() 方法之前执行。
该注解的方法在整个Bean初始化中的执行顺序:
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5703611.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存