|
| 1 | +package com.baeldung.value; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | + |
| 5 | +import javax.annotation.PostConstruct; |
| 6 | + |
| 7 | +import org.springframework.beans.factory.annotation.Value; |
| 8 | +import org.springframework.context.ApplicationContext; |
| 9 | +import org.springframework.context.annotation.AnnotationConfigApplicationContext; |
| 10 | +import org.springframework.context.annotation.Bean; |
| 11 | +import org.springframework.context.annotation.Configuration; |
| 12 | +import org.springframework.context.annotation.PropertySource; |
| 13 | + |
| 14 | +@Configuration |
| 15 | +@PropertySource(name = "myProperties", value = "values.properties") |
| 16 | +public class ValuesApp { |
| 17 | + |
| 18 | + @Value("string value") |
| 19 | + private String stringValue; |
| 20 | + |
| 21 | + @Value("${value.from.file}") |
| 22 | + private String valueFromFile; |
| 23 | + |
| 24 | + @Value("${systemValue}") |
| 25 | + private String systemValue; |
| 26 | + |
| 27 | + @Value("${unknown_param:some default}") |
| 28 | + private String someDefault; |
| 29 | + |
| 30 | + @Value("${priority}") |
| 31 | + private String prioritySystemProperty; |
| 32 | + |
| 33 | + @Value("#{systemProperties['priority']}") |
| 34 | + private String spelValue; |
| 35 | + |
| 36 | + @Value("#{systemProperties['unknown'] ?: 'some default'}") |
| 37 | + private String spelSomeDefault; |
| 38 | + |
| 39 | + @Value("#{someBean.someValue}") |
| 40 | + private Integer someBeanValue; |
| 41 | + |
| 42 | + @Value("#{'${listOfValues}'.split(',')}") |
| 43 | + private List<String> valuesList; |
| 44 | + |
| 45 | + public static void main(String[] args) { |
| 46 | + System.setProperty("systemValue", "Some system parameter value"); |
| 47 | + System.setProperty("priority", "System property"); |
| 48 | + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesApp.class); |
| 49 | + } |
| 50 | + |
| 51 | + @Bean |
| 52 | + public SomeBean someBean() { |
| 53 | + return new SomeBean(10); |
| 54 | + } |
| 55 | + |
| 56 | + @PostConstruct |
| 57 | + public void afterInitialize() { |
| 58 | + System.out.println(stringValue); |
| 59 | + System.out.println(valueFromFile); |
| 60 | + System.out.println(systemValue); |
| 61 | + System.out.println(someDefault); |
| 62 | + System.out.println(prioritySystemProperty); |
| 63 | + System.out.println(spelValue); |
| 64 | + System.out.println(spelSomeDefault); |
| 65 | + System.out.println(someBeanValue); |
| 66 | + System.out.println(valuesList); |
| 67 | + } |
| 68 | +} |
0 commit comments