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

Atomist automates your software deliver experience. It's how modern teams deliver modern software.

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.

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}