springboot获取bean的几种常用方式

举报
object 发表于 2022/06/18 11:28:01 2022/06/18
【摘要】 集成redis时,需要经常操作StringRedisTemplate,直接使用StringRedisTemplate,操作不便,需要依赖注入,工具类封装,调整为静态方法,便于各处调用,因此需要获取上下文,便于工具使用。本文主要从3个方面,共计5种常用的方式获取上下文,从而获取bean。一、第一个主要方面为,启动项目时,通过保存 ApplicationContext。1.xml手动配置方式,获...

集成redis时,需要经常操作StringRedisTemplate,直接使用StringRedisTemplate,操作不便,需要依赖注入,工具类封装,调整为静态方法,便于各处调用,因此需要获取上下文,便于工具使用。


本文主要从3个方面,共计5种常用的方式获取上下文,从而获取bean。

一、第一个主要方面为,启动项目时,通过保存 ApplicationContext。

1.xml手动配置方式,获取容器

// 其中applicationContext.xml 为配置容器的xml,不过现在一般很少使用了
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");

2.springboot主入口启动时,保存上下文

@SpringBootApplication
public class RedisexampleApplication {

    public static void main(String[] args) {
        // 启动时,保存上下文,并保存为静态
        ConfigurableApplicationContext applicationContext = SpringApplication.run(RedisexampleApplication.class, args);
        SpringContextUtil1.setAc(applicationContext);
    }

}
/**
 * 第一种
 * spring获取bean
 * 通过保存ApplicationContext对象
 *
 * @author object
 * @since 2022年6月15日
 */
public class SpringContextUtil1 {

    private static ApplicationContext ac;

    public static <T>  T getBean(String beanName, Class<T> clazz) {
        // 行不通,报错,需要配置文件方式初始化spring的情况
//        ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
        T bean = ac.getBean(beanName, clazz);
        return bean;
    }

    public static void setAc(ApplicationContext applicationContext){
        ac = applicationContext;
    }
}


二、第二个方面主要通过继承的spring提供的接口或者类

1.通过实现ApplicationContextAware 

   推荐!!

/**
 * 第三种
 * spring获取bean
 * 通过实现ApplicationContextAwre方式
 *
 * @author object
 * @since 2022年6月15日
 */
@Component
public class SpringContextUtil3 implements ApplicationContextAware {

    private static ApplicationContext ac;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ac = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        T bean = ac.getBean(clazz);
        return bean;
    }

}

2.通过继承ApplicationObjectSupport

/**
 * 第四种
 * spring获取bean
 * 通过继承ApplicationObjectSupport
 *
 * @author object
 * @since 2022年6月15日
 */
@Service
public class SpringContextUtil4 extends ApplicationObjectSupport {
    public <T> T getBean(Class<T> clazz) {
        T bean = getApplicationContext().getBean(clazz);
        return bean;
    }
}

3.通过继承WebApplicationObjectSupport

/**
 * 第五种
 * spring获取bean
 * 通过继承WebApplicationObjectSupport
 *
 * @author object
 * @since 2022年6月15日
 */
@Service
public class SpringContextUtil5 extends WebApplicationObjectSupport {

    public <T> T getBean(Class<T> clazz) {
        T bean = getApplicationContext().getBean(clazz);
        return bean;
    }

}

三、通过spring提供的静态方法获取上下文

1.通过WebApplicationContextUtils,适用于web项目的b/s结构

/**
 * 第二种
 * spring获取bean
 * 通过servletContext获取bean
 *
 * @author object
 * @since 2022年6月15日
 */
public class SpringContextUtil2 {

    public static <T> T getBean(ServletContext request, String name, Class<T> clazz){
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request);
        // 或者
        WebApplicationContext webApplicationContext1 = WebApplicationContextUtils.getWebApplicationContext(request);
//        webApplicationContext1.getBean(name, clazz)
        T bean = webApplicationContext.getBean(name, clazz);
        return bean;
    }

}

其它:

2.通过ContextLoader获取WebApplicationContext,获取上下文,由于调试中,并没有调试成功,返回值为null,应该和项目的启动方式有关,需要使用特定的方式初始化,这里不做延伸。


对各个方式的使用,做如下列表示例:

StringRedisTemplate为特殊依赖类,自测时,使用自定义的类,并在容器中注册的类即可。

注意:SpringContextUtil4和SpringContextUtil5需要依赖注入,主要是实现父类方法,父类方法为非静态方法。

@RequestMapping("/test")
@RestController(value = "/test")
public class TestApi {

    @Autowired
    TestService testService;

    @Autowired
    SpringContextUtil4 springContextUtil4;

    @Autowired
    SpringContextUtil5 springContextUtil5;

    @RequestMapping("/getobject/{key}")
    public User getObject(HttpServletRequest request, @PathVariable(value = "key") String key) {
        // 第一种
        StringRedisTemplate bean1 = SpringContextUtil1.getBean("stringRedisTemplate", StringRedisTemplate.class);
        // 第二种
        StringRedisTemplate bean2 = SpringContextUtil2.getBean(request.getServletContext(), "stringRedisTemplate", StringRedisTemplate.class);
        // 第三种
        StringRedisTemplate bean3 = SpringContextUtil3.getBean(StringRedisTemplate.class);
        // 第四种
        StringRedisTemplate bean4 = springContextUtil4.getBean(StringRedisTemplate.class);
        // 第五种
        StringRedisTemplate bean5 = springContextUtil5.getBean(StringRedisTemplate.class);
        return testService.getObject(key);
    }
}

调用该方式,展示获取结果:==由于贴图始终贴不上,相当郁闷,那就没办法了,看来博客的编辑器还是有问题,只能直接展示代码==


五种方式均获取成功。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200