Spring中使用@Autowired注解创建静态对象

在Spring里,我们不能@Autowired一个静态变量,使之成为一个spring bean。但静态方法里面的变量必然要使用静态成员变量。例如下面这样:

public class TestUtils {

    @Autowired
    private static DocService docService;

    public static void CallUtil(){
        docService.callMethod();
    }

}

原因

在Spring中,是无法直接使用@Autowired注解到静态变量上,产生一个静态对象的。因为当Java的类加载器启动时,会先加载静态变量,而此时Spring上下文尚未加载,所以类加载器无法在bean中准确注入静态类,导致空指针异常。

解决方法

方法一

给静态组件加setter方法,并在这个方法上加上@Autowired

@Component
public class TestUtils {

    private static DocService docService;

    @Autowired
    public void setDocService(DocService docService){
        TestUtils.docService=docService;
    }

    public static void CallUtil(){
        docService.callMethod();
    }

}

方法二

将@Autowired 注解到类的构造函数上

@Component
public class TestUtils {

    private static DocService docService;
    
    @Autowired
    public TestUtils(DocService docService){
        TestUtils.docService=docService;
    }

    public static void CallUtil(){
        docService.callMethod();
    }

}

方法三

定义一个静态组件,定义一个非静态组件并加上@Autowired注解,再定义一个初始化组件的方法并加上@PostConstruct注解

@Component
public class TestUtils {

    private static DocService docService;

    @Autowired
    private DocService autoDocService;

    @PostConstruct
    private void beforeInit() {
        docService = autoDocService;
    }

    public static void CallUtil() {
        docService.callMethod();
    }

}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值