如何手动获取 Spring 容器中的 bean?

ApplicationContextAware 接口的做用html

先来看下 Spring API 中对于 ApplicationContextAware 这个接口的描述:java

便是说,当一个类实现了这个接口以后,这个类就能够方便地得到 ApplicationContext 中的全部bean。换句话说,就是这个类能够直接获取Spring配置文件中,全部有引用到的bean对象。ajax

如何使用 ApplicationContextAware 接口?spring

如何使用该接口?很简单。intellij-idea

一、定义一个工具类,实现 ApplicationContextAware,实现 setApplicationContext方法ide

public class SpringContextUtils implements ApplicationContextAware { 
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        SpringContextUtils.context = context;
    }

    public static ApplicationContext getContext(){
        return context;
    }

}

如此一来,咱们就能够经过该工具类,来得到 ApplicationContext,进而使用其getBean方法来获取咱们须要的bean。spring-boot

二、在Spring配置文件中注册该工具类工具

之因此咱们能如此方便地使用该工具类来获取,正是由于Spring可以为咱们自动地执行 setApplicationContext 方法,显然,这也是由于IOC的缘故,因此必然这个工具类也是须要在Spring的配置文件中进行配置的。性能

<bean id="springContextUtils" class="com.zker.common.util.SpringContextUtils" />

三、编写方法进行使用idea

一切就绪,咱们就能够在须要使用的地方调用该方法来获取bean了。

public String ajaxRegister() throws IOException {
        UserDao userDao = (UserDao)SpringContextUtils.getContext().getBean("userDao");
        if (userDao.findAdminByLoginName(loginName) != null
                || userDao.findUserByLoginName(loginName) != null) {
            message.setMsg("用户名已存在");
            message.setStatus(false);
        } else {
            message.setMsg("用户名能够注册");
            message.setStatus(true);
        }

        return "register";
    }
做者:Dulk\
来源: https://www.cnblogs.com/deng-...
近期热文推荐:

1.Java 15 正式发布, 14 个新特性,刷新你的认知!!

2.终于靠开源项目弄到 IntelliJ IDEA 激活码了,真香!

3.我用 Java 8 写了一段逻辑,同事直呼看不懂,你试试看。。

4.吊打 Tomcat ,Undertow 性能很炸!!

5.《Java开发手册(嵩山版)》最新发布,速速下载!

以为不错,别忘了随手点赞+转发哦!

相关文章
相关标签/搜索