ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

工具类中采用静态注入的方式来注入bean

2022-06-10 16:33:23  阅读:120  来源: 互联网

标签:switchConfig CommonUtils bean static key public 类中 注入


方式一:

@Component
public class CommonUtils {
 
    private static SwitchConfig switchConfig;
 
    @Autowired
    public void setSwitchConfig(SwitchConfig switchConfig) {
        CommonUtils.switchConfig = switchConfig;
    }
 
    
    /***
     *
     *工具类的静态方法
     ***/
    public static String getSwitchValue(String key){
          
           return switchConfig.getValue(key);
    }
 
    
}

总结:

1.需要对工具类增加@Component 注解;

2.将要注入的bean在工具类中申明下,用static修饰下;

3.给要注入的bean生成setter方法,切记一定不能是静态的,同时要用注解@Autowired;

4.然后再这个工具类中的静态方式里使用了;

 

方式二:

@Component
public class CommonUtils {
 
    @Autowired
    private SwitchConfig switchConfig;
 
    private static CommonUtils commonUtils;
    
    @PostConstruct
    public void init() {
        commonUtils = this;
    }
 
    /***
     *
     *工具类的静态方法
     ***/
    public static String getSwitchValue(Sting key) {
        
          return commonUtils.switchConfig.getValue(key);
    }
    
}

总结:

1.需要对工具类增加@Component 注解;

2.@Autowired 注解注入bean;

3.@PostConstruct 使用该注解定义init()方法,在方法中给当前对象赋值,@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;

 

方式三:

xml中配置bean

<!--spring容器中配置要注入的bean -->
<bean id="commonUtil" class="com.ambitious.CommonUtil" init-method="init"> 
     <property name="switchConfig" ref="switchConfig" />
</bean>

代码中引用

@Component
public class CommonUtils {
 
    private static SwitchConfig switchConfig;
 
  
   /**
     * set方法
     * @param switchConfig
     */
    public static void setVenderInfoService(SwitchConfig switchConfig) {
        CommonUtils.switchConfig = switchConfig;
    }
    
    
    public static String getSwitchValue(String key) {
        return switchConfig.getValue(key);
    }
    
}

 

————————————————
版权声明:本文为CSDN博主「zhangfx5」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010526028/article/details/106807907

标签:switchConfig,CommonUtils,bean,static,key,public,类中,注入
来源: https://www.cnblogs.com/418836844qqcom/p/16363678.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有