Java编程中spring boot项目获取spring容器applicationContext

位置:首页>博客>详情   分类:Java教程   阅读(581)   2023-03-28 11:29:14
Java编程中spring boot项目如何获取spring容器applicationContext

代码如下:
package com.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * 
 * <pre>
 * [Summary]
 * spring boot项目中获取spring容器applicationContext
 * [Detail]
 * TODO
 * [Author]
 * Leftso
 * [Version]
 * v1.0
 * 2017年3月18日下午6:10:13
 * </pre>
 */
@Component
public class SpringUtils implements ApplicationContextAware {
	Logger log=LoggerFactory.getLogger(SpringUtils.class);
	public static ApplicationContext applicationContext = null;

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		if (SpringUtils.applicationContext == null) {
			SpringUtils.applicationContext = arg0;
		}
		
		log.info("Spring 容器对象:"+applicationContext);

	}

	/**
	 * @return the applicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	

}
启动项目,注意观察日志:
容器对象实例
上图可以看出容器对象已经在,在需要获得容器的地方注解如该类,就可以通过get方法随时获取spring的applicationcontext容器进行其他操作
地址:https://www.leftso.com/article/118.html