-1

I haven't seen such question anywhere, so I'm going to ask here about it. I have to make few instances of one object type, the number of how many instances I must instance should be provided from the file .properties. I tried using annotations @Value but it's always giving me

NullPointerException

since the value is null. So for example I have

application.properties

in my resources folder. Let's say the file look like this:

instances.number=5 ...

I use annotation:

@Value("${instances.number}")
private static String lastIndex;

And I want to use it in such way:

psvm {
for(int i = 0; i < Integer.parseInt(lastIndex); i++) {
//creating an instance of object
 }
}

So I cannot parse it since it's null value. What should I do to get instances.number value properly?

...

Tadeusz M
  • 1
  • 1
  • 1
  • 1
    Just like `@Autowired`, injecting values with `@Value` only works in Spring beans. If your class is not a Spring bean, then these annotations do nothing and your field will remain `null`. – Jesper Jul 09 '21 at 09:50

3 Answers3

0

It might be because Spring doesn't support @Value on static fields.

Maybe try something like:

@Component
public class PropertyClass {

    @Value("${lastIndex}")
    private integer lastIndex;

    private static Integer LAST_INDEX;

    @Value("${lastIndex}")
    public void setLastIndex(Integer lastIndex){
        PropertyClass.LAST_INDEX = lastIndex;
    }
}

Resource: https://www.baeldung.com/spring-inject-static-field

Mo_-
  • 574
  • 3
  • 6
0

You can delete static and try it

@Value("${instances.number}")
private String lastIndex;
Yiao SUN
  • 908
  • 1
  • 8
  • 26
0

If you would like to get value by @Value you should annotated class atleast @Component then it will assign value at runtime.

@Service
Public class Config{
@Autowried
 Environment env:

@Value("${instances.number}")
private String lastIndex;

public void test(){
 
System.out.println(env.getProperty("key"));
System.out.println(lastIndex)
}

If you would like to avoid such above problem you can use

environment.getProperty("keyName")
S. Anushan
  • 728
  • 1
  • 6
  • 12