0
@Value("${db.schema.name}")
private String dbSchemaName;

private final String QUERY = 
        "SELECT * " +
        "FROM " + dbSchemaName + ".product "  +
        "WHERE id = :id";

I use the static String "Query" for multiple methods. The variable dbSchemaName is defined in application.properties (db.schema.name).

public List<Object> loadData(final String id){
   final MapSqlParameterSource parameters = new MapSqlParameterSource();
   parameters.addValue("id", id);
   return jdbcTemplate.query(QUERY, parameters, new RowMapperResultSetExtractor<>(mapper)));
}

If i execute the Method loadData(...), the dbSchemaName will not be resolved.

If i change the Query from a String variable to a method, the dbSchemaName will be resolved correctly.

private final getQuery(){
        "SELECT * " +
        "FROM " + dbSchemaName + ".product "  +
        "WHERE id = :id";
}

but I want to get Access of dbSchemaName in the Query String. For me dbSchemaName is always null in the private final String QUERY. Or is there better design than making it a method?

java java
  • 405
  • 1
  • 11
  • 25
  • Instead of field injection use setter injection to inject to static fields – pvpkiran Apr 13 '18 at 12:10
  • 1
    Possible duplicate of [How to assign a value from application.properties to a static variable?](https://stackoverflow.com/questions/45192373/how-to-assign-a-value-from-application-properties-to-a-static-variable) – Patrick Apr 13 '18 at 12:12
  • I have edit my post. – java java Apr 13 '18 at 12:24
  • I have updated my post. I don't want to make it static, i want want to get Access of dbSchemaName in the Query String. dbSchemaName is always null – java java Apr 13 '18 at 12:55
  • you have access to the value in any method with the annotation `@PostConstruct` ... – fingerprints Apr 13 '18 at 12:56

1 Answers1

0

In your non-working code sample java constructs the QUERY string before Spring has injected the value of ${db.schema.name} into dbSchemaName and it is, therefore, null.

Either stick to your method example or inject the whole query from properties:

@Value("${db.query.value}")
private String query;

Where db.query.value is:

SELECT * FROM ${db.schema.name}.product WHERE id = :id
Andy Brown
  • 11,766
  • 2
  • 42
  • 61