This question already has answers here:
Why is my Spring @Autowired field null?
(17个答案)
去年关闭。
我正在尝试在此类中使用Autowired,但是变量config始终为null ...在其他类中,Autowired可以工作。
该项目是由jhipster生成的,我不知道是否存在关系
(17个答案)
去年关闭。
我正在尝试在此类中使用Autowired,但是变量config始终为null ...在其他类中,Autowired可以工作。
该项目是由jhipster生成的,我不知道是否存在关系
@Component
@WebService(endpointInterface = "SignaturePortTypeV2")
public class Signature extends SpringBeanAutowiringSupport implements SignaturePortTypeV2 {
@Autowired
ConfigServiceBean config;
@Override
public ExecuteTokenCmdRespType executeTokenCmd(ExecuteTokenCmdReqType tokenCmdReq) throws ICPMException {
config.getValue(CommonConfigKey.COMPANY_IDENTIFIER);
return null
}
}
@Service
public class ConfigServiceBean implements ConfigServiceLocal {
@Autowired
private Environment env;
@SuppressWarnings("unchecked")
@Override
public <T> T getValue(ConfigKey configKey) {
switch (configKey.getType()) {
case STRING:
return (T) env.getProperty(configKey.getKey(), String.class, configKey.getDefaultValue());
case INT:
return (T) env.getProperty(configKey.getKey(), Integer.class, configKey.getDefaultValue());
case LONG:
return (T) env.getProperty(configKey.getKey(), Long.class, configKey.getDefaultValue());
case DOUBLE:
return (T) env.getProperty(configKey.getKey(), Double.class, configKey.getDefaultValue());
case BOOLEAN:
return (T) env.getProperty(configKey.getKey(), Boolean.class, configKey.getDefaultValue());
default:
throw new IllegalStateException("Type not expected: " + configKey.getType());
}
}
}
最佳答案
我看到一些奇怪的事情:
您说config变量为null,但是使用@Autowired注释。由于需要注入,它应该在Spring Context Load中失败(默认情况下,@ Autowired的属性为required = true)。因此,第一个问题是:是否正在创建bean签名?可能是@Configuration注释的类(或者您创建了spring上下文)正在寻找另一个包。
executeTokenCmd方法始终返回null。它只是从env中检索一个值,然后返回null。这真的没有道理。这可能是您出错的原因吗?
如果您可以粘贴错误跟踪,它将有所帮助。