如何以编程方式创建 Spring 属性?

huangapple go评论97阅读模式
英文:

How to create spring property programatically?

问题

我可以通过将其添加到yml或properties文件中轻松创建新属性:my.custom.property=5。但是我如何可以从代码中实现相同的功能呢?类似于:

@SomeSpringAnnotation("my.custom.property")
fun myFun() = 5

或者

registerProperty("my.custom.property", 5)
英文:

I can easily create new property by adding it to yml or properties file: my.custom.property=5. but how can i do the same from the code? sth like:

@SomeSpringAnnotation("my.custom.property")
fun myFun() = 5

or

registerProperty("my.custom.property", 5)

答案1

得分: 1

通过使用自定义工厂添加 @PropertySource 可以创建动态的 PropertySource

尽管我没有尝试过。对于某些属性来说,它可能评估得太了。我个人也认为动态创建属性不是一个很好的主意。在我看来,更好的解决方案是定制正在使用该属性的代码。

另一种方法是使用带有 EL 表达式的 @Value,类似于 @Value("#{someBean.someValue}")

英文:

Adding @PropertySource with custom factory allows for creating dynamic PropertySource.

I did not try it though. Ii might also be evaluated too late for some properties. I personally also think it is not very good idea to create properties dynamically. Customizing the code which is using the property would be better solution IMO.

Another approach would be using @Value with EL expression along the lines of @Value("#{someBean.someValue}").

答案2

得分: 0

程序化?我不认为这有意义!编程属性和常量之间有什么区别?

如果您想要创建一个高级属性,@Value注解的默认值表达式是一个不错的方法。例如:@Value("${my.custom.property:5}") private int myCustomProperty;

英文:

programatically?i don't think it's meaningful! what's the difference between a programatical property and a constant?

if you want to create a property advanced, the default-value expression of Value annotation is a good way.eg.@Value("${my.custom.property:5}") private int myCustomProperty;

答案3

得分: 0

请看,System.setProperty(...) 或者 System.setProperties(),这些方法可以用来在运行时设置属性。

英文:

Have a look at, System.setProperty(...) or System.setProperties(), those methods can be used to set properties at runtime.

huangapple
  • 本文由 发表于 2020年10月23日 16:46:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64496820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定