Spring项目的类中获取ApplicationContext实例的方式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring项目的类中获取ApplicationContext实例的方式相关的知识,希望对你有一定的参考价值。

获取ApplicationContext实例的方式:

1.实现ApplicationContextAware接口

新增自定义类,并实现ApplicationContextAware接口,Spring加载该类时会自动调用setApplicationContext方法。

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationUtil implements ApplicationContextAware{
    
    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // TODO Auto-generated method stub
        
        this.applicationContext = applicationContext;
        
    }

}

 

以上是关于Spring项目的类中获取ApplicationContext实例的方式的主要内容,如果未能解决你的问题,请参考以下文章

自定义一个SpringUtil用于通过静态方法获取被spring管理的bean对象,用于在静态方法中使用IOC中的bean或者是没有被spring管理的类中使用IOC容器的bean

SpringBoot中在普通类里面加载Spring容器中的类

03-Spring的IOC示例程序(通过类型获取对象)

Spring:在Junit中加载的类中自动装配不同的类

spring初始化相关

java如何在一个普通的类中获取request对象