Search code examples
springspring-annotations

Does every instantiated class in spring load default variables from the application.properties file?


Spring annotations question. I am using a default value like so

@Service
public class MyClient{
@Value("${apikey}")
private String apikey;
    public MyClient(){}
}

I imagine that every instantiation of this class should initialize the value of apikey to the default value apikey from the application.properties file. Is this not so? I ask because I am finding apikey to be null after I've instantiated MyClient object.


Solution

  • Your class is annotated @Service and so it is a spring-managed bean. By default all spring beans are singleton so exists in only one instance.

    If you try to create this bean manually auto wiring of @value won't work because you bypass the spring initialization.

    Btw: it is a bad idea to mix self-managed and spring-managed bean from the same class.