0

I need to set two values in Spring bean property value having same name.

Currently I have

I am using this property name as this in Java class : private String siteUid;

My requirement is to add another property name with diffrent value

Please suggest, if I can write both property values, and how can I use the same in Java class

PriyaS
  • 142
  • 2
  • 14
  • 1
    Well, a Spring bean property always refers to a field of the corresponding Java class and there can not be 2 fields with the same name in a class – DanielBK Jan 30 '20 at 12:15
  • 2
    Does this answer your question? [Reading a List from properties file and load with spring annotation @Value](https://stackoverflow.com/questions/12576156/reading-a-list-from-properties-file-and-load-with-spring-annotation-value) – NikNik Jan 30 '20 at 12:30

3 Answers3

1

You can use the @Value annotation.

If you have a properties file that contains:

foo.bar.property1=hello
foo.bar.property2=world

You can use in your Java class:

@Component
public class SomeClass {

    @Value("${foo.bar.property1}")
    private String variable1;  // will be set to "hello"

    @Value("${foo.bar.property2}")
    private String variable2;  // will be set to "world"
}

Note that the names of the actual variables (i.e. variable1 and variable2) are irrelevant; they can be whatever you want. The important part is that the string contained in @Value matches the key in your properties file.

cameron1024
  • 9,083
  • 2
  • 16
  • 36
0

Its not really clear what do you mean by adding. In general as long as you're supposed to use @Value annotation the most flexible approach by far, is using Values in autowired constructor:

@Component
public class MyComponent {
   private String myProperty;

   public MyComponent(@Value('${app.value1}') String value1, @Value('${app.value2}') String value2) {
      // here you can even concatenate the value (hence I've said that its not clear what is 'add' but in general you can manipulate however you want
     this.myProperty = value1 + value2; 
   }

}
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

You could use Spring Expression Language here to add/concat two property

@Value("#{'${property1}'.concat('${property2}')}") String parameter

Here concat is the String method. As the requirement is not very clear to me, so you could experiment with other string methods to achieve what you want.

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41