April 17, 2015

Spring Sweets: Using @Value for Constructor Arguments

In 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.*

class Message {

    final String text

    // Use @Autowired to get @Value to work.
        // Refer to configuration property
        // app.message.text to set value for 
        // constructor argument text.
        @Value('${app.message.text}') final String text) {
        this.text = text


Written with Spring 4.1.6.