Several methods for Spring to obtain ApplicationContext

Links to related articles:

SSM framework to build a Web project

IDEA uses Maven to build SSM framework web projects

Tips before viewing:

The IDEA version used in this article is ultimate 2019.1, the JDK version is 1.8.0_141, and the Tomcat version is 9.0.12.

The examples in this article are in the framework of the above link reference article.

1. Introduction to ApplicationContext

Practical Bean factory ApplicationContext.

The Chinese meaning of ApplicationContext means "application context". It inherits from the BeanFactory interface. In addition to including all the functions of BeanFactory, it also provides good support in terms of internationalization support, resource access (such as URLs and files), and event propagation. It is recommended as the first choice for Java EE applications and can be used in Java APP and Java Web.

2. How to Obtain

2.1 Obtained through the tool class WebApplicationContextUtils provided by Spring

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext);

ac1.getBean(Class);
ac2.getBean("beanId");

Instance

UserService.java

package com.example.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    


    public void insertUser() {
    
    
        System.out.println("插入用户成功");
    }

    public boolean updateUser() {
    
    
        System.out.println("更新用户成功");
        return true;
    }
}

Part of the test method in the interceptor RequestMappingInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    

    ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());

    UserService u1 = ac1.getBean(UserService.class);
    UserService u2 = ac2.getBean(UserService.class);
    u1.insertUser();
    u2.updateUser();

    return super.preHandle(request, response, handler);
}

Test Results
Insert picture description here
Note: This method is suitable for the B/S system using the Spring framework to obtain the ApplicationContext object through the ServletContext object, and then obtain the required class instance through it.

2.2 Save the ApplicationContext object during initialization

ApplicationContext ac1 = new ClassPathXmlApplicationContext("**/applicationContext.xml");

(Class) ac1.getBean("beanId");
ac1.getBean(Class);

Instance

The structure is as follows
Insert picture description here

applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="testApplicationContext"></context:component-scan>
</beans>

TestApplicationContext.java

package testApplicationContext;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestApplicationContext{
    
    

    @Test
    public void test() {
    
    
        try {
    
    
            ApplicationContext ac1 = new ClassPathXmlApplicationContext("testApplicationContext/applicationContext.xml");

            UserService u1 = (UserService) ac1.getBean("userService");
            UserService u2 = ac1.getBean(UserService.class);
            u1.insertUser();
            u2.updateUser();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

The results are as follows
Insert picture description here

Note: This method is suitable for independent applications using the Spring framework and requires the program to manually initialize Spring through the configuration file.

2.3 Inherited from the abstract class ApplicationObjectSupport

Instance

ApplicationObjectSupportUtil.java

package com.example.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

@Component
public class ApplicationObjectSupportUtil extends ApplicationObjectSupport {
    
    

    private static ApplicationContext applicationContext;

    /**
     * 重写方法,注入applicationContext
     * @param applicationContext
     */
    @Override
    public void initApplicationContext(ApplicationContext applicationContext) {
    
    
        this.applicationContext = applicationContext;
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(String name) {
    
    
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
    
    
        checkApplicationContext();
        return (T) applicationContext.getBean(clazz);
    }

    /**
     * 清除applicationContext静态变量.
     */
    public static void cleanApplicationContext() {
    
    
        applicationContext = null;
    }

    private static void checkApplicationContext() {
    
    
        if (applicationContext == null) {
    
    
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
}

Part of the test method in the interceptor RequestMappingInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
    UserService userService = ApplicationObjectSupportUtil.getBean(UserService.class);
    userService.insertUser();
    return super.preHandle(request, response, handler);
}

The results are as follows
Insert picture description here

Note: The abstract class ApplicationObjectSupport provides the getApplicationContext() method, which can easily obtain the ApplicationContext. When Spring is initialized, the ApplicationContext object will be injected through the setApplicationContext(ApplicationContext context) method of this abstract class.

2.4 Inherited from the abstract class WebApplicationObjectSupport

Instance

WebApplicationObjectSupportUtils.java

package com.example.util;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationObjectSupport;

@Component
public class WebApplicationObjectSupportUtils extends WebApplicationObjectSupport {
    
    

    private static ApplicationContext applicationContext;

    /**
     * 重写方法,注入applicationContext
     * @param applicationContext
     */
    @Override
    public void initApplicationContext(ApplicationContext applicationContext) {
    
    
        this.applicationContext = applicationContext;
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(String name) {
    
    
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
    
    
        checkApplicationContext();
        return (T) applicationContext.getBean(clazz);
    }

    /**
     * 清除applicationContext静态变量.
     */
    public static void cleanApplicationContext() {
    
    
        applicationContext = null;
    }

    private static void checkApplicationContext() {
    
    
        if (applicationContext == null) {
    
    
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
}

Part of the test method in the interceptor RequestMappingInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
    UserService userService = WebApplicationObjectSupportUtils.getBean(UserService.class);
    userService.insertUser();
    return super.preHandle(request, response, handler);
}

The results are as follows

Insert picture description here

Note: Similar to the above method, you can also call getWebApplicationContext() to get WebApplicationContext

2.5 Implement the interface ApplicationContextAware

Instance

SpringContext.java

package com.example.util;

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

@Component
public class SpringContextUtil implements ApplicationContextAware {
    
    

    private static ApplicationContext applicationContext; // Spring应用上下文环境

    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
    
    
        SpringContextUtil.applicationContext = applicationContext;
    }
    /**
     * 获取Spring应用上下文环境
     */
    public static ApplicationContext getApplicationContext() {
    
    
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 清除applicationContext静态变量.
     */
    public static void cleanApplicationContext() {
    
    
        applicationContext = null;
    }

    /**
     * 获取对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
    
    
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 获取类型为requiredType的对象
     */
    public static <T> T getBean(Class<T> clz) {
    
    
        checkApplicationContext();
        return applicationContext.getBean(clz);
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     */
    public static boolean containsBean(String name) {
    
    
        checkApplicationContext();
        return applicationContext.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     */
    public static boolean isSingleton(String name) {
    
    
        checkApplicationContext();
        return applicationContext.isSingleton(name);
    }

    /**
     * Class 注册对象的类型
     */
    public static Class<?> getType(String name) {
    
    
        checkApplicationContext();
        return applicationContext.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名,则返回这些别名
     */
    public static String[] getAliases(String name) {
    
    
        checkApplicationContext();
        return applicationContext.getAliases(name);
    }

    /**
     * 检查applicaitonContext是否注入
     */
    private static void checkApplicationContext() {
    
    
        if (applicationContext == null) {
    
    
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
}

Part of the test method in the interceptor RequestMappingInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
    UserService userService = SpringContext.getBean(UserService.class);
    userService.insertUser();
    return super.preHandle(request, response, handler);
}

The results are as follows
Insert picture description here

Note: Implement the setApplicationContext(ApplicationContext context) method of this interface and save the ApplicationContext object. When Spring is initialized, the ApplicationContext object will be injected through this method.

Guess you like

Origin blog.csdn.net/weixin_43611145/article/details/103038626