Spring injects static variables

       This article wrote an example to implement Spring injection of static variables. The reason why static variables cannot be injected directly is that the initialization of static variables is carried out when the class loader is loaded, which is earlier than the time when the web engine is started. One solution is to inject in the form of variable injection at execution time.

 

package com.my.util;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.my.dao.ICacheService;

/**
 * Cache tool class
 * @author aeolus
 *
 */
@Component
public class CacheUtil {
	// static variables that need to be injected
	private static ICacheService SERVICE;
	
	/**
	 * This method can set static variables, similar to dependency injection
	 * @param cacheService
	 */
	@Resource(name = "cacheService")
	private void setCacheService(ICacheService cacheService) {
		CacheUtil.SERVICE = cacheService;
	}

	public static  void setValue(String key,Object value){
		SERVICE.setValue(key, value);
	}
	
	public static Object getValue(String key) {
		return SERVICE.getObject(key);
	}

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326329057&siteId=291194637