返回顶部

利用SpringBeanUtil 来获取 IOC 容器中的bean

有时候在代码中,不希望使用自动注入,而是手动获取Spring容器以及Spring容器中的某个对象

1、首先写一个class实现ApplicationContextAware#

复制代码
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 @Component
public class SpringBeanUtil implements ApplicationContextAware {
 
    private static ApplicationContext applicationContext;
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }
 
    /**
     * 通过名称在spring容器中获取对象
     * 
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }
 
}
复制代码

2、在代码调用SpringBeanUtil的getBean获取指定的bean对象了

https://www.cnblogs.com/houchen/p/14005211.html

posted @   fen斗  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示