[英]In Spring, how do I create a POJO with a default value from configuration?
I am using the Spring framework to with a properties file that has the key: 我正在使用Spring框架来处理具有关键字的属性文件:
empty.value = -
I would like to be able to create a POJO that would have that empty value as its default value for the default constructor of the POJO. 我希望能够创建一个POJO,该POJO会将空值作为POJO的默认构造函数的默认值。 Something like this:
像这样:
public class Dog {
private String name;
public Dog(){
}
public Dog(String name){
this.name = name;
}
}
So that if Dog d = new Dog()
is called, d.name
will be -
from the empty.value
key. 所以,如果
Dog d = new Dog()
被调用时, d.name
会-
从empty.value
关键。
Autowiring the name
variable will just be null
because Spring isn't aware of the POJO as well as using @Value("${empty.value}")
. 自动装配
name
变量将为null
因为Spring不了解POJO,也不使用@Value("${empty.value}")
。
What would be the best way of achieving this? 实现这一目标的最佳方法是什么?
Edit : To clarify, there are meant to be many Dog
s throughout the system and I need to be able to initialize them on request. 编辑 :澄清一下,整个系统中有很多
Dog
,我需要能够根据要求初始化它们。
Edit 2 : Consider the following use case- I have an interface containing a method: 编辑2 :考虑以下用例-我有一个包含方法的接口:
Dog transform(List<String> animals);
I would like to be able to know that whatever Dog
is returned from the transform method has either -
(configurable) as a name
or a different value passed in to the constructor when created (or setter, later). 我希望能够知道,从transform方法返回的任何
Dog
都具有-
(可配置)作为name
或者在创建时(或稍后使用setter)传递给构造函数的其他值。 I would like to ensure that for whatever transform
does in any implementation, even if it fails, I will have a valid Dog
with a name
as mentioned. 我想确保无论在任何实现中进行任何
transform
,即使transform
失败,我都会拥有一个有效的Dog
,其name
如上所述。
If you are using the Spring framework, you have to create all your Spring beans using also Spring. 如果使用Spring框架,则必须同时使用Spring创建所有Spring Bean。 For example:
例如:
Dog d = (Dog)context.getBean("dog");
Doing Dog d = new Dog()
is a valid instance, but that way it's not processed by Spring. 做
Dog d = new Dog()
是有效的实例,但是那样Spring不会对其进行处理。
Update about the Edit 2 有关编辑2的更新
If you want to ensure you always have a valid dog instance when calling the transform
method, you can use a try catch
block in the caller code. 如果要确保在调用
transform
方法时始终具有有效的dog实例,则可以在调用者代码中使用try catch
块。 For example: 例如:
// caller class
Dog dog = null;
try{
dog = yourInterface.transform(animals);
if (dog == null || !validName(dog.name)){
throw new RuntimeException("Not a valid dog/name");
}
}catch(Exception ex){
dog = (Dog)context.getBean("dog");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.