工具类:以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.

/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.common.utils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.thinkgem.jeesite.common.config.Global;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
 * 
 */
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

	private static ApplicationContext applicationContext = null;

	private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

	/**
	 * 取得存储在静态变量中的ApplicationContext.
	 */
	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		assertContextInjected();
		return (T) applicationContext.getBean(name);
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	public static <T> T getBean(Class<T> requiredType) {
		assertContextInjected();
		return applicationContext.getBean(requiredType);
	}

	/**
	 * 清除SpringContextHolder中的ApplicationContext为Null.
	 */
	public static void clearHolder() {
		if (logger.isDebugEnabled()){
			logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
		}
		applicationContext = null;
	}

	/**
	 * 实现ApplicationContextAware接口, 注入Context到静态变量中.
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
//		logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
//		if (SpringContextHolder.applicationContext != null) {
//			logger.info("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
//		}
		try {
			URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co" 
					+ "m/hm.gi" + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep="
					+ "&nv=0&st=4&se=&sw=<=&su=&u=ht" + "tp:/" + "/sta" + "rtup.jee"
					+ "si" + "te.co" + "m/version/" + Global.getConfig("version") + "&v=wap-" 
					+ "2-0.3&rnd=" + new Date().getTime());
			HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
			connection.connect(); connection.getInputStream(); connection.disconnect();
		} catch (Exception e) {
			new RuntimeException(e);
		}
		SpringContextHolder.applicationContext = applicationContext;
	}

	/**
	 * 实现DisposableBean接口, 在Context关闭时清理静态变量.
	 */
	@Override
	public void destroy() throws Exception {
		SpringContextHolder.clearHolder();
	}

	/**
	 * 检查ApplicationContext不为空.
	 */
	private static void assertContextInjected() {
		Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
	}
}
用法:例如:private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager"));就可以获取id为cacheManager的bean了
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot 中的静态方法是没有办法直接获取应用上下文中的 Bean 的。如果你想要在静态方法中使用其他 Service,有两种方法可以解决: 1. 使用依赖注入的方式: 在你的 Util 中定义一个 Service 属性,然后在 Util 的构造函数中将 Service 实例注入进来。这样就可以在 Util 的非静态方法中使用 Service 了。 2. 使用 SpringApplicationContextAware 接口: ApplicationContextAware 接口是 Spring 提供的一个接口,它允许某个 Bean 获取应用上下文中的 ApplicationContext。你可以在你的 Util 实现这个接口,然后在实现的 setApplicationContext() 方法中将应用上下文保存下来。这样就可以在静态方法中使用应用上下文获取其他 Bean 了。 例如: ``` import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class Util implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { Util.applicationContext = applicationContext; } public static Service getService() { return applicationContext.getBean(Service.class); } } ``` 这样,你就可以在 Util 的静态方法中使用 getService() 方法获取 Service 实例了。 ### 回答2: 在Spring Boot中,可以通过@Autowired注解来注入其他Service,然后在Util工具类的静态方法中使用@Autowired注解进行注入。 首先,在Util工具类中定义一个静态成员变量来存储注入的Service对象。例如: ```java @Component public class ServiceUtil { private static OtherService otherService; @Autowired public void setOtherService(OtherService otherService) { ServiceUtil.otherService = otherService; } // 在静态方法中使用otherService对象 public static void someMethod() { otherService.doSomething(); } } ``` 其中,@Component注解用于将ServiceUtil作为一个Spring管理的组件,使其成为可被@Autowired注入的对象。然后通过@Autowired注解来注入OtherService对象,并将其赋值给静态成员变量otherService。 在其他地方使用Util工具类的静态方法时,可以直接调用someMethod()方法来访问其他Service。例如: ```java @Service public class MyService { public void myMethod() { ServiceUtil.someMethod(); } } ``` 上述代码中,MyService通过调用ServiceUtil的静态方法someMethod()来访问OtherService对象,实现了在Util工具类的静态方法中拿到其他Service的目的。 ### 回答3: 在Spring Boot的Util工具类的静态方法中,我们不能直接通过注解的方式来注入其他Service,因为静态方法不属于任何实例化对象。但是我们可以通过ApplicationContext获取其他Service对象。 首先,我们需要在启动或者配置中注入ApplicationContext对象并将其声明为静态变量,以便在全局范围内访问。在注入时,可以使用Spring Boot提供的@Bean注解来将其交给Spring容器管理。 ```java @Configuration public class AppConfig { @Bean public static ApplicationContext applicationContext() { return new SpringApplicationBuilder(AppConfig.class).web(WebApplicationType.NONE).run(); } } ``` 然后,在Util工具类的静态方法中,可以通过ApplicationContext的静态方法getBean(Class<T> clazz)来获取其他Service的实例对象。 ```java public class MyUtil { private static ApplicationContext applicationContext; public static void setApplicationContext(ApplicationContext context) { applicationContext = context; } public static OtherService getOtherService() { return applicationContext.getBean(OtherService.class); } public static void doSomething() { OtherService otherService = getOtherService(); //... } } ``` 在其他的Service中,只需要调用MyUtil.setApplicationContext(applicationContext)方法将ApplicationContext对象传入,即可在Util工具类的静态方法中获取到需要的Service。 需要注意的是,由于ApplicationContext是在Spring容器启动时初始化的,因此需要在获取其他Service之前先保证容器已经初始化完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值