@Autowired bean 在静态方法中显示为 null



我有两个类名,分别是Bean类和Util类。在 Util 类中,我想从 Bean 类调用该方法。但问题是当我在 Util 课上@Autowired豆类时。由于 Util 类中的静态方法,存在空指针异常。这是我的代码。

public class Util{
@Autowired
private static BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean;
private static String PASSPHRASE = baseServiceCommonPropertiesBean.getBassURL();
System.out.print(PASSPHRASE);
}

这里是 BaseServiceCommonPropertiesBean 类

public class BaseServiceCommonPropertiesBean {
@Value("#{baseServiceapplicationProperties['mobi.sc.travellers.amr.email.base.url']}")
private String baseUrl;
public String getBaseUrl(){
return baseUrl;
}
}

每当系统读取baseServiceCommonPropertiesBean.getPassPhrase((方法时。它出去并停止工作.我尝试@Postconstruct注释之前它不起作用。谢谢。

您不能@Autowired静态字段,可以从 BaseServiceCommonPropertiesBean 中删除静态字段,或者将 Util 重写为如下所示的内容:

@Component
public class Util{
private static BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean;
@Autowired
public void setBaseServiceCommonPropertiesBean(BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean){
Util.baseServiceCommonPropertiesBean = baseServiceCommonPropertiesBean;
}
private static String PASSPHRASE = baseServiceCommonPropertiesBean.getBassURL();
System.out.print(PASSPHRASE);
}

最新更新