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;
        
    }

}

 

posted on 2021-06-03 11:48  pcant  阅读(225)  评论(0编辑  收藏  举报