Search code examples
javaspringannotations

how to use strings which annotation with @Value in order to join the other strings?


I want to use Strings which have Annotation @Value but If I try them join to another a string they turns a null object.If I use just them they works well.What I need to do use them to join another a string or those strings cannot join other strings?

 @Value("${Example.com}")
private String HOST_NAME;

private String BASE_URL="http://"+HOST_NAME+":8080";

System.out.println(HOST_NAME);
// Output is 123.123.123.1123;(For example)
System.out.println(BASE_URL);
// Output like that http://null:8080;

Solution

  • Here :

    private String BASE_URL="http://"+HOST_NAME+":8080";
    

    HOST_NAME is null because in Java, field initializers are evaluated before the class constructor but at the Spring startup, Spring values fields annotated with @Value such as :

    @Value("${Example.com}")
    private String HOST_NAME;
    

    only after the constructor be invoked.

    So to solve your requirement, set BASE_URL in the constructor such as :

    private String BASE_URL;
    public FooClass(){
       BASE_URL="http://"+HOST_NAME+":8080";
    }
    

    Not your question but you could use a constructor injection with @Value. It makes the class less Spring dependent and more unit-testable.

    private String BASE_URL;
    private String HOST_NAME;
    
    public FooClass(@Value("${Example.com}") String hostName){
       this.HOST_NAME = hostName;
       this.BASE_URL="http://"+HOST_NAME+":8080";
    }