Close

Spring Framework - @Value Examples

Spring Framework 

    public static class MyBean {
@Value("#{systemProperties['user.home']}")
private String userHome;

public void showProp () {
System.out.println(userHome);
}
}
Original Post




    public static class MyBean {
@Value("${some-prop:defaultStr}")
private String str;

public void showProp () {
System.out.println(str);
}
}
Original Post




In this example, @Value param 'theCurrency' value is auto converted to Currency object. Spring does this implicit conversion using property editors. In this example CurrencyEditor is used behind the scene.

package com.logicbig.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.Currency;

public class JConfigPropertySourceExample {

public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(Config.class);
ClientBean bean = context.getBean(ClientBean.class);
bean.doSomething();
}

@Configuration
@PropertySource("classpath:app.properties")
public static class Config {
@Bean
public ClientBean clientBean () {
return new ClientBean();
}
}

public static class ClientBean {
@Value("${theCurrency}")
private Currency currency;

public void doSomething () {
System.out.printf("The currency from prop file is %s%n", currency);
System.out.printf("The currency name is %s%n", currency.getDisplayName());
}
}
}

Output

The currency from prop file is PLN
The currency name is Polish Zloty

src/main/resources/app.properties:

theCurrency=PLN
thePrice=12,323.7654
theTradeDate=2016-9-14
Original Post




See Also