user998692
user998692

Reputation: 5256

How does @Value work in SpEL?

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?

Upvotes: 0

Views: 324

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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.

Upvotes: 2

Related Questions