以静态的方法使用spring中的bean

1.SpringContextHolder.java

package com.Nightliar.business.common.utils;

import com.Nightliar.business.entity.SysMenu;
import com.Nightliar.business.enums.CacheType;
import com.Nightliar.business.service.ISysMenuService;
import com.Nightliar.business.shiro.ShiroUser;
import com.Nightliar.business.utils.BackendLoginUtil;
import com.Nightliar.business.utils.Constant;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *
 * Created by Nightliar
 * 2018-03-25 20:59
 *
 */

@Component
public class UserUtils {

    @Autowired
    private static ISysMenuService menuService = SpringContextHolder.getBean(ISysMenuService.class);

    /**
     * 得到当前用户权限下的所有资源
     */
    @SuppressWarnings("unchecked")
    public static List<SysMenu> getMyListMenu(){
        ShiroUser shiroUser = BackendLoginUtil.getUser();
        List<SysMenu> menuList = (List<SysMenu>)CacheUtils.get(CacheType.CACHE_SYSCACHE.getCode(), Constant.SYSCACHE_USER_INDEXMENU + shiroUser.getId());
        if (menuList == null){
            EntityWrapper<SysMenu> wrapper = new EntityWrapper<>();
            wrapper.orderBy("sort");
            wrapper.in("id", shiroUser.getMenuIds());
            menuList = menuService.selectList(wrapper);
            CacheUtils.put(CacheType.CACHE_SYSCACHE.getCode(), Constant.SYSCACHE_USER_INDEXMENU + shiroUser.getId(), menuList);
        }
        return menuList;
    }

}

2.CacheUtils.java(实例)

package com.Nightliar.business.common.utils;

import com.Nightliar.business.enums.CacheType;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.util.List;

/**
  *
 * Created by Nightliar
 * 2018-3-29 21:50
 *
 */
public class CacheUtils {
	
	private static CacheManager cacheManager = (CacheManager)SpringContextHolder.getBean("ehcacheManager");

	//默认为系统缓存
	private static final String SYS_CACHE = CacheType.CACHE_SYSCACHE.getCode();

	/**
	 * 获取SYS_CACHE缓存
	 * @param key
	 */
	public static Object get(String key) {
		return get(SYS_CACHE, key);
	}

    /**
     * 获取缓存
     * @param cacheName
     * @param key
     */
    public static Object get(String cacheName, String key) {
        Element element = getCache(cacheName).get(key);
        return element==null?null:element.getObjectValue();
    }
	
	/**
	 * 写入SYS_CACHE缓存
	 * @param key
	 * @return
	 */
	public static void put(String key, Object value) {
		put(SYS_CACHE, key, value);
	}

    /**
     * 写入缓存
     * @param cacheName
     * @param key
     * @param value
     */
    public static void put(String cacheName, String key, Object value) {
        Element element = new Element(key, value);
        getCache(cacheName).put(element);
    }
	
	/**
	 * 从SYS_CACHE缓存中移除
	 * @param key
	 * @return
	 */
	public static void remove(String key) {
		remove(SYS_CACHE, key);
	}
	
	/**
	 * 从缓存中移除
	 * @param cacheName
	 * @param key
	 */
	public static void remove(String cacheName, String key) {
		getCache(cacheName).remove(key);
	}

    /**
     * 从缓存中删除某一类型的缓存
     * @param cacheName
     */
	public static void removeCache(String cacheName){
	    getCache(cacheName).removeAll();
    }
	
	/**
	 * 获得一个Cache,没有则创建一个。
	 * @param cacheName
	 * @return
	 */
	public static Cache getCache(String cacheName){
		Cache cache = cacheManager.getCache(cacheName);
		if (cache == null){
			cacheManager.addCache(cacheName);
			cache = cacheManager.getCache(cacheName);
			cache.getCacheConfiguration().setEternal(true);
		}
		return cache;
	}

	public static CacheManager getCacheManager() {
		return cacheManager;
	}
	
}

<think>我们正在讨论的是如何在Spring框架中通过静态方法获取ApplicationContext,进而获取Bean实例。根据引用内容,我们可以实现一个类实现ApplicationContextAware接口,这样Spring容器在初始化时会将ApplicationContext注入到该类中。然后我们可以在这个类中提供一个静态方法,以便在其他地方通过这个静态方法获取ApplicationContext,进而获取Bean。步骤如下:1.创建一个类(通常称为SpringContextHolder)实现ApplicationContextAware接口。2.在该类中定义一个静态的ApplicationContext变量。3.在setApplicationContext方法中将传入的ApplicationContext赋值给静态变量。4.提供一个静态方法(如getApplicationContext)返回ApplicationContext。5.提供另一个静态方法(如getBean)用于获取Bean实例。注意:由于ApplicationContext是在Spring容器启动时注入的,因此要确保这个类被Spring管理(比如通过@Component注解)。下面是一个示例:</think>在Spring框架中,通过静态方法获取Bean实例需要以下步骤: ### 解决方案 1. **实现ApplicationContextAware接口** 创建工具类实现`ApplicationContextAware`接口,Spring容器初始化时会自动注入`ApplicationContext`实例: ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext ctx) throws BeansException { applicationContext = ctx; // 静态变量接收容器实例[^1] } public static <T> T getBean(Class<T> clazz) { return applicationContext.getBean(clazz); } } ``` 2. **通过静态方法获取Bean** 在其他类的静态方法中直接调用工具类: ```java public class SomeUtils { public static void doSomething() { // 静态获取Bean实例 MyService service = SpringContextHolder.getBean(MyService.class); service.execute(); } } ``` ### 关键说明 - **实现原理**:Spring容器检测到`ApplicationContextAware`接口时,会在Bean初始化后自动调用`setApplicationContext()`注入容器实例[^1] - **线程安全**:静态`ApplicationContext`在容器启动后初始化,多线程访问安全 - **作用域限制**:无法在Bean初始化阶段使用(此时容器未完成注入) - **替代方案**:也可直接注入`ApplicationContext`到非静态字段,但不符合静态调用需求 ### 使用示例 ```java // 测试类 public class Main { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); MyBean bean = SpringContextHolder.getBean(MyBean.class); // 静态获取[^3] bean.run(); } } ``` > **注意**:此方式会引入Spring依赖到静态上下文中,建议仅在工具类等特殊场景使用,优先使用常规依赖注入。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值