Question

I have a class A with a date field annotated with @Value to take as default value the current date.

When I create a bean in an XML file, this field appears to be initialized with the current date, as expected.

When I create a new object with new A() in main of a test class, the field is null.

My question is how does @Value work. In the documentation, it said it gives a default value to a field, but does it work only for beans? How is it processed?

Was it helpful?

Solution

When creating the bean using the XML file, Spring creates the bean and applies the injection of configured fields, via XML configuration or decorated by annotations e.g. @Autowired, @Value, etc...

When creating the bean using new YourClass, then you're manually creating an instance of the class, thus not being handled by Spring.

If you want Spring to handle new beans created on demand i.e. using new keyword, you can refer to Spring injecting or autowiring datasource bean to class, point 3 and the explanation at the bottom using @Configurable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top