Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Value in Springboot returns null

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);
    }
}
like image 717
NicO Avatar asked Nov 26 '18 13:11

NicO


4 Answers

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.

like image 64
NicO Avatar answered Oct 25 '22 19:10

NicO


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.

like image 23
Omkar Pisal Avatar answered Oct 25 '22 19:10

Omkar Pisal


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).

like image 9
Urosh T. Avatar answered Oct 25 '22 19:10

Urosh T.


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.

like image 1
snmaddula Avatar answered Oct 25 '22 20:10

snmaddula