首页 > 解决方案 > 属性值注入 Spring bean

问题描述

我想知道为什么@Value属性注入适用于带有@Service注释的类,但不适用于带有注释类@Bean@Configuration类。

Works 意味着属性值不为空。

这个值也被注入到我在调试过程中看到的另外两个服务中DefaultListableBeanFactory.doResolveDependency。但我没有看到豆子WebserviceEndpoint

配置

@Configuration
public class WebserviceConfig {

   // do some configuration stuff

   @Bean
   public IWebserviceEndpoint webserviceEndpoint() {
      return new WebserviceEndpoint();
   }

}

网络服务接口

@WebService(targetNamespace = "http://de.example/", name = "IWebservice")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface IWebserviceEndpoint {
    @WebMethod
    @WebResult(name = "response", targetNamespace = "http://de.example/", partName = "parameters")
    public Response callWebservice(@WebParam(partName = "parameters", name = "request", targetNamespace = "http://de.example/") Request request) throws RequestFault;
}

网络服务类

public class WebserviceEndpoint implements IWebserviceEndpoint {

   @Value("${value.from.property}")
   private String propertyValue;

}

应用程序.yml

value:
 from:
  property: property-value

在这种情况下,@Value 的注入何时发生。

标签: springspring-bootinversion-of-control

解决方案


基本上propertyValue是 null 因为 Spring 在 bean 创建后注入值。所以当你这样做时:

@Bean
public IWebserviceEndpoint webserviceEndpoint() {
  return new WebserviceEndpoint();
}

Spring 使用propertyValue=null. 您可以使用初始化您的实例属性@ConfigurationProperties

@Bean
@ConfigurationProperties(prefix=...)
public IWebserviceEndpoint webserviceEndpoint() {
   return new WebserviceEndpoint();
}

注意propertyValue应该有一个setter。

您有多种方法可以解决此问题,通常最好将属性集中在一个 utils 类中。

@Component
public class Configs {
  @Value("${propery}"
  String property;

  String getProperty(){ 
    return property;
  }
}

进而:

@Bean
@ConfigurationProperties(prefix=...)
public IWebserviceEndpoint webserviceEndpoint() {
    WebserviceEndpoint we = new WebserviceEndpoint();
    we.setProperty(configs.getProperty())
   return we;
}

同样有许多不同的方法来解决这个问题


推荐阅读