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

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

Spring的核心是ApplicationContext,它负责管理 beans 的完整生命周期。我们可以从applicationContext里通过bean名称获取注入的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,这样就可以使用了。

下面是一段使用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使用雪花算法的工具类可以通过创建一个SnowflakeManager类来实现。首先,你需要创建一个SnowflakeProperties类,该类使用lombok注解@Getter和@Setter来自动生成getter和setter方法,并定义了machineId和dataCenterId两个属性。\[1\]然后,你可以创建一个BossAutoConfiguration类,该类使用@EnableConfigurationProperties注解来使@ConfigurationProperties注解的类生效。在BossAutoConfiguration类,你可以使用@Autowired注解来注入TestProperties类,并使用@Bean注解和@ConditionalOnMissingBean注解来创建一个SnowflakeManager的bean。在SnowflakeManager的构造函数,你可以使用properties对象获取machineId和dataCenterId的值,并将其传递给SnowflakeManager的实例化对象。\[3\]这样,你就可以在Spring Boot使用雪花算法的工具类了。 #### 引用[.reference_title] - *1* *3* [spring boot雪花算法](https://blog.csdn.net/qq_33327680/article/details/125599943)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Spring Boot项目下JPA自定义雪花算法ID生成器详解](https://blog.csdn.net/wjw465150/article/details/125301120)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值