spring - 属性值注入 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 的注入何时发生。
解决方案
基本上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;
}
同样有许多不同的方法来解决这个问题
推荐阅读
- minecraft - 将 systemctl 与 Minecraft 服务器服务一起使用时出现权限错误
- android-studio - 如何将 Firestore 时间戳数据设置为 TextView
- git - “已经是最新的”Git 消息不正确
- swift - Firestore:如何使用 documentID 读取子集合数据?
- c++ - 使用宏的编译时条件类型操作
- python - 为什么我收到属性错误:'time.struct_time' 对象没有属性'sleep'?
- python - 遍历 json 并解析键值对
- android - Xamarin.Forms ListView Android 上的重复项
- r - R:如何在 dplyr 中使用 mutate 进行分组?
- php - 如何在 laravel 中编写空白 php?