静态类变量的注入

@Component
public class GenericAndJson {

    private static ObjectMapper mapper;

    @Autowired
    public void setMapper(ObjectMapper mapper) {
        GenericAndJson.mapper = mapper;
    }

    public static xxx (){}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,静态类中使用注入需要借助Spring提供的工具类`ApplicationContextAware`。具体步骤如下: 1. 定义一个静态类,实现`ApplicationContextAware`接口,重写`setApplicationContext()`方法。 ```java public class StaticClass implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { StaticClass.applicationContext = applicationContext; } public static Object getBean(String name) { return applicationContext.getBean(name); } } ``` 2. 在静态类中定义一个静态成员变量`applicationContext`,用于保存ApplicationContext对象。 3. 在`setApplicationContext()`方法中,将ApplicationContext对象保存到静态成员变量`applicationContext`中。 4. 在静态类中定义一个静态方法`getBean(String name)`,用于获取Bean实例。 5. 在静态方法中使用静态成员变量`applicationContext`获取Bean实例。 例如,我们要在静态类中使用`UserService`进行业务操作,可以使用如下代码: ```java public class StaticClass implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { StaticClass.applicationContext = applicationContext; } public static UserService getUserService() { return applicationContext.getBean(UserService.class); } } ``` 这样,我们就可以在静态类中使用注入的Bean实例了。注意,使用静态类中的注入需要保证Spring容器已经启动,否则可能会出现空指针异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值