2

My current code when I use inputstream. prop = new properties;

 Application = prop.getProperty("Application");
 servers = prop.getProperty("SERVERS");
 username = prop.getProperty("USER_NAME");
 password = prop.getProperty("PASSWORD");
Float criticalThreshold = Float.parseFloat(prop.getProperty("THRESHOLD_CRITICAL"));
Float badThreshold = Float.parseFloat(prop.getProperty("THRESHOLD_BAD"));   

I recently implemented my application properties into my java class using spring boots way.

@Value("${Application}")
private String Application;
@Value("${SERVERS}")
private String servers; 
@Value("${USER_NAME}")
private String username;
@Value("${PASSWORD}")
private String password;

But I do not know how to rewrite the Float.parseFloat

    Float criticalThreshold = Float.parseFloat(prop.getProperty("THRESHOLD_CRITICAL"));
Float badThreshold = Float.parseFloat(prop.getProperty("THRESHOLD_BAD"));

I tried but it automatically gives me an compiler error.

@Value("${THRESHOLD_CRITICAL}")
    private Float criticalThreshold;
@Value("${THRESHOLD_BAD}")
    private Float badThreshold;
Jodi
  • 1,874
  • 6
  • 37
  • 69

2 Answers2

2

You can refer the solution suggested by Alex as it does not require the additional variable like in the below approach.

You can't directly do that, but you can achieve that @PostConstruct and declaring one more variable criticalThresholdFloatValue like below:

@Value("${THRESHOLD_CRITICAL}")
private String criticalThreshold;

private float criticalThresholdFloatValue;

@PostConstruct
public void init() {
    criticalThresholdFloatValue = Float.parseFloat(criticalThreshold);
}

Now, you can start using criticalThresholdFloatValue where ever you are using in the bean methods.

developer
  • 20,716
  • 8
  • 46
  • 63
  • Would it be possible to annotate the a setter method like in this example? http://stackoverflow.com/questions/317687/how-can-i-inject-a-property-value-into-a-spring-bean-which-was-configured-using – Joe Essey Nov 04 '16 at 15:17
  • Joe: I am not sure how to do that, but my approach above works, but needs additional var. – developer Nov 04 '16 at 15:30
2

@Value lets you specify a method to call to alter the injected property:

@Value("#{T(java.lang.Float).parseFloat('${THRESHOLD_CRITICAL}')}")
private float criticalThreshold;

I tested it and it also works without the full package name:

@Value("#{T(Float).parseFloat('${THRESHOLD_CRITICAL}')}")
private float criticalThreshold;
alexbt
  • 15,503
  • 6
  • 73
  • 85