首页 > 解决方案 > WebService类中的Spring Autowired不起作用

问题描述

我正在尝试在此类中使用 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());
        }
    }
}

标签: javaspringweb-servicesspring-bootwsimport

解决方案


我看到一些奇怪的事情:

  1. 您说配置变量为空,但是,它使用@Autowired 进行了注释。它应该在 Spring Context Load 中失败,因为需要注入(@Autowired 默认具有属性 required = true)。所以第一个问题是:bean Signature 是否正在创建?可能是您的 @Configuration 注释类(或者您创建弹簧上下文)正在查看另一个包。
  2. 方法 executeTokenCmd 总是返回 null。它只是从环境中检索一个值,然后返回 null。这真的没有意义。这可能是您错误的原因吗?

如果您可以粘贴错误跟踪,这将有所帮助。


推荐阅读