【问题标题】:Spring Autowired in WebService Class not working [duplicate]WebService类中的Spring Autowired不起作用[重复]
【发布时间】:2019-01-30 21:44:51
【问题描述】:

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

【问题讨论】:

  • 1) 你怎么知道? 2) 您如何获得Signature 实例? 3)executeTokenCmd方法什么时候执行?
  • 好吧,我发布了一个带端点的接口,像这样:Endpoint.publish("http://127.0.0.1:9876/ws", new Signature());,当我调用这个接口时,executeTokenCmd 被执行,例如通过 SOAPUI。
  • 好吧,您没有回答我的第一个问题,但基于您“手动”执行new Signature() 而不是从 Spring 上下文中获取实例的事实,这很正常,因为 Spring 不会知道您的实例,因此注入不会“神奇地”发生。这很可能是 Why is my Spring @Autowired field null? 的副本
  • 另一个使用构造函数注入而不是字段/设置器的理由 :-)

标签: java spring web-services spring-boot wsimport


【解决方案1】:

我看到了一些奇怪的东西:

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

如果您可以粘贴错误跟踪信息会有所帮助。

【讨论】:

  • 感谢您抽出宝贵时间回复并提供帮助。但是,这并不能直接解决问题,根据 SO 理念,应通过comments 而不是答案来添加建议或要求澄清和进一步的细节。
  • 感谢您告诉我。我在这方面是全新的。下次我会更小心的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 2016-03-25
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多