0

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)
piotrek
  • 13,982
  • 13
  • 79
  • 165
  • Just add it into the properties manager. – Zorglube Oct 23 '20 at 09:09
  • @Zorglube i coulnd't find such spring class. can u plz elaborate or give a few lines of code? – piotrek Oct 23 '20 at 09:16
  • You can through reload properties method to realize change property value in runtime.[How to hot-reload properties in Java EE and Spring Boot?](https://stackoverflow.com/questions/52594764/how-to-hot-reload-properties-in-java-ee-and-spring-boot) – TongChen Oct 23 '20 at 09:27

3 Answers3

1

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}").

Michal
  • 2,353
  • 1
  • 15
  • 18
0

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;

pigman
  • 86
  • 7
  • because instead of `5` it can be `complexRuntimeComputation()` – piotrek Oct 23 '20 at 09:07
  • i think what you show is property autowiring, not property creation – piotrek Oct 23 '20 at 09:09
  • 1
    @piotrek - @Value can evaluate an expression using EL with the `#` syntax, e.g. `@Value("#{someBean.someValue}")` . – Michal Oct 23 '20 at 09:33
  • why don't you call the method instead of property creation ?im sorry that i still don't know what you want to do.how about Cache with annotation of PutCache and Cachable? – pigman Oct 26 '20 at 03:15
0

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

akuma8
  • 4,160
  • 5
  • 46
  • 82
  • but is there a way to just create a spring property and not to polute env with new env variables? – piotrek Oct 23 '20 at 09:12