我有两个类名,分别是Bean类和Util类。在Util类中,我想从Bean类中调用该方法。但问题是,当我@Autowired将Bean类自动转换为Util类时。由于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);
}
添加注释会很好用,它们可以是@Service
或@Component
之类的东西
@Service
public class BaseServiceCommonPropertiesBean {
@Value("#{baseServiceapplicationProperties['mobi.sc.travellers.amr.email.base.url']}")
private String baseUrl;
public String getBaseUrl() {
return baseUrl;
}
}