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

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容器进行其他操作

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

相关文章:

你感兴趣的文章:

标签云: