zoukankan      html  css  js  c++  java
  • spring与springboot中,如何在static方法里使用自动注入的属性

    第一步:写注解@Component 使当前类成为一个bean对象。(@Controller,@service都行)

    第二步:写个static的变量

    第三步:写个@PostConstruct注解注解注释的方法,在这个方法里,将自动注入的值赋值给定义的static变量

    第四步:static变量替代自动注入在static方法里面使用

    @Component
    public class DSHWechatApiUtil extends DSHBaseController {

        @Autowired
        private IThirdPartyAuthDao thirdPartyAuthDao; @Autowired
    private static IThirdPartyAuthDao staticThirdPartyAuthDao; @PostConstruct public void init() { staticThirdPartyAuthDao = thirdPartyAuthDao; } public static JSONObject getAuthorizerToken(String componentAccessToken, String authorizerAppid, String authorizerRefreshToken) { JSONObject returnObject = new JSONObject(); try { if (DSHUtils.isEmpty(componentAccessToken)) { componentAccessToken = staticThirdPartyAuthDao.selectWechatValue(DSHConstants.WECHAT_PARAMS.COMPONENT_ACCESS_TOKEN); } } catch (Exception e) { e.printStackTrace(); } return returnObject; } }

    @PostConstruct注解作用:是Java EE 5引入的注解,Spring允许开发者在受管Bean中使用它。当DI容器实例化当前受管Bean时,@PostConstruct注解的方法会被自动触发,从而完成一些初始化工作。

    注意:

    • 只有一个方法可以使用此注释进行注解;
    • 被注解方法不得有任何参数;
    • 被注解方法返回值为void;
    • 被注解方法不得抛出已检查异常;
    • 被注解方法需是非静态方法;
    • 此方法只会被执行一次;

    参考文章:

    https://blog.csdn.net/qq_23167527/article/details/77994677

    https://blog.csdn.net/wo541075754/article/details/52174900

  • 相关阅读:
    mfc窗口,父窗口parentwindow,所有者窗口ownerwindow 区别
    svn冲突问题详解 SVN版本冲突解决详解
    input的on(‘input’,function(0{})事件
    input 输入框两种改变事件的方式
    JSON格式
    AJAX的dataType问题
    什么是跨域请求?
    JSON.parse()和JSON.stringify()使用介绍
    .replace(/-/g,"/")的用法
    docker 实践(一)
  • 原文地址:https://www.cnblogs.com/BobXie85/p/8745705.html
Copyright © 2011-2022 走看看