I have the application.properties, which is located in the resources
apllication.properties
hsm.provider=software
hsm.name=TestHsm
hsm.port=3001
hsm.ip=127.0.0.1
hsm.timeout=10000
and the Controller
@RestController
@RequestMapping("/hsm")
public class Controller {
@Value("${hsm.ip}")
private String ip;
@Value("${hsm.port}")
private String port;
@Value("${hsm.name}")
private String name;
@Value("${hsm.timeout}")
private String timeout;
@Value("${hsm.provider}")
private String provider;}
}
however when i run application, all variables remain NULL. What am i missing?
EDIT This is the projectstructure as of the src folder
src
├───main
│ ├───java
│ │ └───com
│ │ └───xyz
│ │ └───hsmservice
│ │ └───hsm
│ │ └───api
│ │ Application.java
│ │ Controller.java
│ │ HSM.java
│ │
│ └───resources
│ │ application.properties
│ │
│ └───META-INF
│ plugin.xml
│
└───test
├───java
│ LibraryTest.java
│
└───resources
EDIT 2 Here is the application class
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Okay, i solved it with the top answer of this Question. I put the variables and @Values in the signature of the constructor and not as class variables.
The reason why @Value returns null sometimes is because when you try to use 'application.properties' contents for static variables which is not allowed in spring. Follow this: https://mkyong.com/spring/spring-inject-a-value-into-static-variables/ and it should work fine.
Judging by your package structure, those properties should definitely be loaded. Only possible option is that you have instantiated your Controller
class as new Controller()
instead of letting spring injecting the class (using @Autowired
or constructor injection).
I've added your code into a Spring boot project and it is in a working condition.
Checkout this 53482633 repository and follow the instructions to get it up and running.
Also compare your code against this application to figure out what was going wrong at your end.
In case if you still face any issues, please post it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With