Over a million developers have joined DZone.

Spring Sweets: Using @Value for Constructor Arguments

DZone 's Guide to

Spring Sweets: Using @Value for Constructor Arguments

· Java Zone ·
Free Resource

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 message.
        @Value('${app.message.text}') final String text) {
        this.text = text


Written with Spring 4.1.6.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}