简体   繁体   中英

Not able to access application.yml properties in springboot component

I have an application.yml file which contains properties as below

NAME:
   CLASS:
     ID: ABC123456

and here is my spring boot component class

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class  ProcessMe {

@Value("${NAME.CLASS.ID}")
String StuId;

public boolean IsRightOrWrong(){
    System.out.println(StuId);
}
}

In above componenent System.out.println(StuId); is always coming as null. When i am tying to call this function using Junit test class. What's wrong in the above code?

I suppose this solution to define in constructor like

@Component
@Slf4j
public class  ProcessMe {

String StuId;

@Autowired
ProcessMe(@Value("${NAME.CLASS.ID}") String StuId) {
    this.StuId = StuId;
}
public boolean IsRightOrWrong(){
    System.out.println(this.StuId);
}
}

Hope useful

If you can start the application then I believe that your configuration is correct. I mean that StuId have some value.

The problem is how you testing When i am tying to call this function using Junit test class. What's wrong in the above code? When i am tying to call this function using Junit test class. What's wrong in the above code?

It seems that you're calling from the unit test. Then you need to clone application.yaml to test profile then your test container can read data, otherwise you have to mock your configuration.

btw: Java Object property should using camel case lol

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM