0

I have been given a task to assign a property from .properties file to a non Spring bean class using @Value annotation. To do this, I created a method on a @Component annotated class and set the property into it, then called that method from the non Spring bean class. I thought this would work, however, still showing as null.

I was told this is because the @Component annotated class I used is not spring loaded. Question, how can I tell if a class is Spring loaded bean? I have been searching on google but can't find anything helpful aside from examples with @Component or @Configuration annotations. Thanks.

message
  • 4,513
  • 2
  • 28
  • 39
Angge
  • 25
  • 8
  • can you share the sample code snippet ? – Madhu Sep 15 '18 at 09:54
  • is this a spring boot application ? – benjamin c Sep 15 '18 at 10:32
  • You'll have to configure Spring so that it finds the `@Component` annotated class and then look it up in the Spring application context. If you instantiate the class with `new MyClass()` then it's not managed by Spring and dependencies and things like `@Value` fields will not be filled in. – Jesper Sep 15 '18 at 10:53
  • See: [Why is my Spring `@Autowired` field null?](https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – Jesper Sep 15 '18 at 10:54
  • You have to enable component scanning in Spring, so your classes annotated with `@Component` will be instantiated by Spring and registered as a Spring bean in the Spring application context. Dependecy injection with the `@Value` annotation will only work if the target object (where the value should be injected) is a true (managed) bean. Other than that and your injected properties/method params etc. will always be null! – Tommy Brettschneider Sep 15 '18 at 11:02
  • Thanks for all your input. – Angge Sep 16 '18 at 20:33

1 Answers1

0

Spring Container is responsible for creating or managing beans. It all satisfy the dependencies by injecting them either through constructor or setter method. But in your case you want the @Value injection in your non spring bean which is really not possible as per my understanding. Because here the spring does not creating the object then how it satisfy the dependencies of it.

You have two options for this situation.

  1. Either annotate class using @Component

  2. Either read property file using Properties

https://www.mkyong.com/java/java-properties-file-examples/

Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18