0

I have a class

 public class Constants {
@Value("${graph.apiSecret")
public static   String API_SECRET;
}

In my application-dev.properties is graph.apiSecret=secretHere property

My test shows API_SECRET as null

@RunWith(SpringRunner.class)
@SpringBootTest
public class GraphViewSiteTest {
    @Test
    public void testgetAllFilesInAFolderOnOurDevSite() throws  ConnectException, IOException, OAuth2AccessTokenErrorResponse, InterruptedException, ExecutionException {
        System.out.println(Constants.API_SECRET);
   }

I am using spring boot 1.5.2

MangduYogii
  • 935
  • 10
  • 24
Daniel Haughton
  • 1,085
  • 5
  • 20
  • 45
  • we’ll first need to define a @PropertySource in our configuration class – with the properties file name. – MangduYogii Aug 16 '19 at 10:27
  • 2
    Possible duplicate of [Spring: How to inject a value to static field?](https://stackoverflow.com/questions/7253694/spring-how-to-inject-a-value-to-static-field) – Madhu Bhat Aug 16 '19 at 10:29
  • Use nonstatic setter... If you are reading anyway from configuration, be as well use @ Configuration bean instead of static member in constants. Note : You also missed ending "}" in Value annotation @ Value – Nagesh Salunke Aug 16 '19 at 12:01

2 Answers2

1

Spring doesn't inject values into static variables, therefore you have to create a non static setter for it:

@Value("${graph.apiSecret]")
public void setApiSecret(String apiSecret){
  API_SECRET= apiSecret;
}
sudo
  • 747
  • 6
  • 19
0

The above answers are true you will have to use non static setter.

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

But you also need to specify properties file path from where it will read.

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Constants.class)
@TestPropertySource("classpath:application-test.properties")  
public class GraphViewSiteTest {

@Test
public void testgetAllFilesInAFolderOnOurDevSite()   {
    System.out.println(Constants.API_SECRET);
   }
}
Himanshu Sharma
  • 560
  • 3
  • 12