Java开发之静态工具方法中注入springBean

2022-07-27,,,,

java开发

    • 常见场景:在静态方法中使用springbean依赖
    • 使用方法
    • 总结

常见场景:在静态方法中使用springbean依赖

在项目开发中经常遇到在静态工具类中使用springbean依赖服务,此时使用注解 @Autowired 常常失效,那如何解决此问题呢?

使用方法

@Component
public class SpringBeanUtills implements ApplicationContextAware {
    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtills.context = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return (T) context.getBean(clazz);
    }

    public static Object  getBean(String name) throws BeansException {
        return context.getBean(name);
    }
}

在静态方法中使用

DemoBean bean = SpringBeanUtills.getBean(DemoBean.class);

即可获得数据springbean依赖调用

总结

在项目开发中,偶尔遇到小问题,经常记录一点帮助自己成长。

本文地址:https://blog.csdn.net/weixin_43841081/article/details/110233431

《Java开发之静态工具方法中注入springBean.doc》

下载本文的Word格式文档,以方便收藏与打印。