0

I have some @Value annotation in spring-boot project. To Simplify, I have few classes: a restcontroller, service (annotated with @Service) and a pojo.
In each of these classes, I declared a variable as below:

@Value("${somevalue}")
private String somevalueVariable
  1. In the controller class, the value is getting populated as defined in the application.properties. So no problem here.
  2. In the service class, the value is showing up as null. This is my issue, how should i fix it to get the value from the application.properties

In the pojo, the value is showing up as null, I am thinking this is expected behaviour as spring does not manage this class.

samshers
  • 1
  • 6
  • 37
  • 84

3 Answers3

1

It uses Spring Expression Language (SpEL):

https://docs.spring.io/spring-integration/docs/5.3.0.RELEASE/reference/html/spel.html

Also there is 2 @Value : org.springframework.beans.factory.annotation.Value and lombok.Value; Make sure you are using the right one.

To get value from property try this:

@Value("${systemValue}")
private String systemValue;

For more information I find this useful: https://www.baeldung.com/spring-value-annotation

Rabhi salim
  • 486
  • 5
  • 17
  • i am using the right annotation - `import org.springframework.beans.factory.annotation.Value;` – samshers Nov 27 '20 at 13:55
  • then how is it working in the restcontroller class but not in the @Service class – samshers Nov 27 '20 at 13:56
  • Weird how its working in controller and not service ... try this https://www.baeldung.com/spring-value-annotation#using-value-with-constructor-injection maybe – Rabhi salim Nov 27 '20 at 14:13
1

Try this:

import org.springframework.beans.factory.annotation.Value;


@Value("#{${somevalue}}")
private String somevalueVariable
im_infamous
  • 972
  • 1
  • 17
  • 29
1

ideally service class should have @Service anotation over it, either you missed that or this class is not scanned by spring context, so please add ComponentScan anotation for service class package over main class to scan classes uner this package -

@SpringBootApplication
@ComponentScan({"com.in28minutes.springboot"})
public class Application 
sanjeevjha
  • 1,439
  • 14
  • 18