• 通过ApplicationContextAware加载Spring上下文环境(转)


    项目用到了ApplicationContextAware,通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。

    我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。

    使用方法如下:

    1.实现ApplicationContextAware接口:

    package com.bis.majian.practice.module.spring.util;
     
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
     
    public class SpringContextHelper implements ApplicationContextAware {
        private static ApplicationContext context = null;
     
        @Override
        public void setApplicationContext(ApplicationContext applicationContext)
                throws BeansException {
            context = applicationContext;
        }
        
        public static Object getBean(String name){
            return context.getBean(name);
        }
        
    }

    2.在Spring的配置文件中配置这个类,Spring容器会在加载完Spring容器后把上下文对象调用这个对象中的setApplicationContext方法:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName">
        
        <bean id="springContextHelper" class="com.bis.majian.practice.module.spring.util.SpringContextHelper"></bean>
        
        <context:component-scan base-package="com.bis.majian.practice.module.*" />
    </beans>

    3.在web项目中的web.xml中配置加载Spring容器的Listener:

    <!-- 初始化Spring容器,让Spring容器随Web应用的启动而自动启动 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>

    4.在项目中即可通过这个SpringContextHelper调用getBean()方法得到Spring容器中的对象了。

    ————————————————
    版权声明:本文为CSDN博主「大饼卷馒头蘸米饭」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/majian_1987/article/details/11170841

  • 相关阅读:
    而立之年的程序员创业者,写给不甘平凡的自己和80、90后!
    无焦虑,不成长!三大方法让你走出焦虑!
    [Chat]实战:仿网易云课堂微信小程序开发核心技术剖析和经验分享
    [干货教程]仿网易云课堂微信小程序开发实战经验
    微信公众号支付之坑:调用支付jsapi缺少参数 timeStamp等错误解决方法
    微信支付之扫码支付开发:我遇到的坑及解决办法(附:Ecshop 微信支付插件)
    OpenCV 4.3 编译和配置
    OpenCV 之 基本绘图
    OpenCV 之 空间滤波
    Qt 地址薄 (二) 添加地址
  • 原文地址:https://www.cnblogs.com/muxi0407/p/12124402.html
Copyright © 2020-2023  润新知