springcontext数组(详解springboot设计模式)


在项目中有时需要根据需要在自己new一个对象,或者在某些util方法或属性中获取Spring Bean对象,从而完成某些工作,但是由于自己new的对象和util方法并不是受Spring所管理的,如果直接在所依赖的属性上使用@Autowired就会报无法注入的错误,或者是没报错,但是使用的时候会报空指针异常。总而言之由于其是不受Spring IoC容器所管理的,因而无法注入。

Spring Boot中通过SpringContextUtil工具类获取容器中Bean对象

Spring的核心是ApplicationContext,它负责管理 beans 的完整生命周期。我们可以从applicationContext里通过bean名称获取注入的bean,然后进行操作。

Spring Boot中通过SpringContextUtil工具类获取容器中Bean对象

SpringContextUtil工具类的代码如下所示:

package com.rickie.util;

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

public class SpringContextUtil {

private static ApplicationContext applicationContext;

// 设置上下文

public static void setApplicationContext(ApplicationContext context) throws BeansException {

applicationContext = context;

}

// 获取上下文

public static ApplicationContext getApplicationContext() {

return applicationContext;

}

// 通过名字获取上下文中的bean

public static Object getBean(String name) {

if(name == null || name.length()==0) {

return null;

}

try {

String beanName = “”;

if(name.length() >1){

beanName = name.substring(0, 1).toLowerCase() + name.substring(1);

} else {

beanName = name.toLowerCase();

}

return applicationContext.getBean(beanName);

} catch (Exception ex){

ex.printStackTrace();

return null;

}

}

// 通过类型获取上下文中的bean

public static <T> T getBean(Class<T> clazz) {

try {

return (T) applicationContext.getBean(clazz);

} catch(Exception ex) {

ex.printStackTrace();

return null;

}

}

}

由于该类并没有实现ApplicationContextAware接口,因此先设置好ApplicationContext的值。可以在Spring Boot的启动方法main中进行设置:

@SpringBootApplication

public class Application {

public static void main(String[] args) {

ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);

SpringContextUtil.setApplicationContext(ctx);

}

}

在Spring Boot的启动时调用的run方法会返回一个
ConfigurableApplicationContext,将其设置到SpringContextUtil的静态属性中,然后能够通过ApplicationContext对象获取到需要使用的bean,这样就可以使用了。

Spring Boot中通过SpringContextUtil工具类获取容器中Bean对象

下面是一段使用SpringContextUtil工具类的示例代码:

/**

* 创建一个新的客户

* @param customer

* @return

*/

public int create(Customer customer) {

if(this.customerGateway == null) {

this.customerGateway = SpringContextUtil.getBean(CustomerGateway.class);

}

return customerGateway.insert(customer);

}

这样,无论是在静态方法中,还是在手动new的实例中,我们都能够成功获取IoC容器所管理的bean。如果我们想在静态属性中获取Spring Bean,其实也非常简单,直接对属性赋值即可,如下所示:

private static Customer customer = SpringBeanUtil.getBean(Customer.class);

Spring Boot中通过SpringContextUtil工具类获取容器中Bean对象

Spring Cloud Alibaba微服务实战技术专栏,从项目实践出发,包括Spring Cloud Alibaba、Nacos、Gateway、Sentinel、Log日志、分布式全局唯一ID、DDD领域驱动设计等等技术内容,可帮助你对Spring Cloud 微服务技术栈有更加全面和直观的了解。相信你通过本专栏的练习和实践,能够学以致用,提升微服务应用的开发能力。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发表评论

登录后才能评论