spring静态注入

spring普通的注入方式是基于类的对象的,static修饰的是基于类本身的,所以用普通的注解去注入静态对象的时候,会报java.lang.NullPointerException空指针运行时异常,这里提供几种种比较常用的spring静态注入的方式,一版在java代码的工具类中使用;

首先在spring容器中配置要注入的bean

<!--spring容器中配置要注入的bean -->
<bean id="switchConfig" class="com.ambitious.SwitchConfig"/>

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

方式一:

@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);
	}
	
}

     

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值