SpringがApplicationContextを取得するためのいくつかのメソッド
関連記事へのリンク:
IDEAはMavenを使用してSSMフレームワークWebプロジェクトを構築します
表示する前のヒント:
この記事で使用されているIDEAバージョンは究極の2019.1、JDKバージョンは1.8.0_141、Tomcatバージョンは9.0.12です。
この記事の例は、上記のリンク参照記事のフレームワークにあります。
1.ApplicationContextの概要
実用的なBeanファクトリApplicationContext。
ApplicationContextの中国語の意味は、「アプリケーションコンテキスト」を意味し、BeanFactoryインターフェイスから継承します。BeanFactoryのすべての機能を含むだけでなく、国際化サポート、リソースアクセス(URLやファイルなど)、およびイベント伝播の面でも優れたサポートを提供します。 Java EEアプリケーションの最初の選択肢として推奨され、JavaAPPおよびJavaWebで使用できます。
2.入手方法
2.1Springが提供するツールクラスWebApplicationContextUtilsを介して取得
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext);
ac1.getBean(Class);
ac2.getBean("beanId");
インスタンス
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;
}
}
インターセプター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);
}
試験結果
注:このメソッドは、Springフレームワークを使用してServletContextオブジェクトを介してApplicationContextオブジェクトを取得し、それを介して必要なクラスインスタンスを取得するB / Sシステムに適しています。
2.2初期化中にApplicationContextオブジェクトを保存します
ApplicationContext ac1 = new ClassPathXmlApplicationContext("**/applicationContext.xml");
(Class) ac1.getBean("beanId");
ac1.getBean(Class);
インスタンス
構成は以下のとおりです。
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();
}
}
}
結果は以下のとおりです。
注:この方法は、Springフレームワークを使用する独立したアプリケーションに適しており、プログラムが構成ファイルを使用してSpringを手動で初期化する必要があります。
2.3抽象クラスApplicationObjectSupportから継承
インスタンス
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");
}
}
}
インターセプター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);
}
結果は以下のとおりです。
注:抽象クラスApplicationObjectSupportは、ApplicationContextを簡単に取得できるgetApplicationContext()メソッドを提供します。Springが初期化されると、ApplicationContextオブジェクトは、この抽象クラスのsetApplicationContext(ApplicationContext context)メソッドを介して挿入されます。
2.4抽象クラスWebApplicationObjectSupportから継承
インスタンス
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");
}
}
}
インターセプター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);
}
結果は以下のとおりです。
注:上記のメソッドと同様に、getWebApplicationContext()を呼び出してWebApplicationContextを取得することもできます。
2.5インターフェイスApplicationContextAwareを実装する
インスタンス
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");
}
}
}
インターセプター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);
}
結果は以下のとおりです。
注:このインターフェースのsetApplicationContext(ApplicationContext context)メソッドを実装し、ApplicationContextオブジェクトを保存します。Springが初期化されると、ApplicationContextオブジェクトがこのメソッドを介して挿入されます。