在开发过程中,我们可能需要动态获取spring容器中的某个bean的实例,此时我们就会用到ApplicationContext spring应用上下文,这里做一下记录,网上很多类似的的工具类。
先写好工具类再测试一下是否好用
工具类:
package com.zhh.demo.common.util;import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;/*** 容器应用上下文工具类* @author zhaoheng*/
@Component
public class ApplicationContextUtil implements ApplicationContextAware {private static ApplicationContext applicationContext;/*** 将注入的 ApplicationContext 赋值给当前类中的applicationContext* @param applicationContext* @throws BeansException*/@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {ApplicationContextUtil.applicationContext = applicationContext;}/*** 获取Spring的应用上下文* @return*/public static ApplicationContext getContext(){return applicationContext;}/*** 根据bean名称获取到容器中的bean* */public static Object getBean(String name) {return applicationContext.getBean(name);}/*** 根据bean类型获取bean* */public static <T> T getBean(Class<T> clazz){return applicationContext.getBean(clazz);}/*** 根据bean类型和名称获取bean* */public static <T> T getBean(String name, Class<T> requiredType) {return applicationContext.getBean(name, requiredType);}}
测试是否好用
创建一个bean并注入到容器
package com.zhh.demo.service;import org.springframework.stereotype.Service;
/*** @Description: 测试bean* @Author: zhaoheng*/
@Service
public class TestService {public void show(){System.out.println("TestService-show...");}
}
测试方法
package com.zhh.demo;import com.zhh.demo.common.util.ApplicationContextUtil;
import com.zhh.demo.service.TestService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class ApplicationTest {@Autowiredprivate ApplicationContextUtil applicationContextUtil;@Testvoid contextTest() {// 通过名称获取容器中的beanTestService userService1 = (TestService) applicationContextUtil.getBean("testService");userService1.show();System.out.println("---------------");// 通过class获取容器中的beanTestService testService2 = applicationContextUtil.getBean(TestService.class);testService2.show();}
}
测试结果: