Spring Sweets: Using @Value for Constructor Arguments
Join the DZone community and get the full member experience.
Join For FreeIn Spring we can use the @Value
annotation to set property or arguments values based on a SpEL expression. If we want to use the @Value
annotation for a constructor argument we must not forget to add the @Autowired
annotation on the constructor as well.
// File: sample/Message.groovy package sample import org.springframework.beans.factory.annotation.* import org.springframework.stereotype.* @Component class Message { final String text // Use @Autowired to get @Value to work. @Autowired Message( // Refer to configuration property // app.message.text to set value for // constructor argument message. @Value('${app.message.text}') final String text) { this.text = text } }
Written with Spring 4.1.6.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments