JAVA-1526: Copy three @Value related articles to spring-boot-properties-2

This commit is contained in:
Krzysztof Woyke 2020-05-20 15:51:11 +02:00
parent c4101d7df7
commit 304a6fb6cc
14 changed files with 379 additions and 4 deletions

View File

@ -3,4 +3,7 @@
This module contains articles about Properties in Spring Boot.
### Relevant Articles:
- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties)
- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties)
- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation)
- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults)
- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class)

View File

@ -0,0 +1,28 @@
package com.baeldung.properties.value;
public class ClassNotManagedBySpring {
private String customVariable;
private String anotherCustomVariable;
public ClassNotManagedBySpring(String someInitialValue, String anotherManagedValue) {
this.customVariable = someInitialValue;
this.anotherCustomVariable = anotherManagedValue;
}
public String getCustomVariable() {
return customVariable;
}
public void setCustomVariable(String customVariable) {
this.customVariable = customVariable;
}
public String getAnotherCustomVariable() {
return anotherCustomVariable;
}
public void setAnotherCustomVariable(String anotherCustomVariable) {
this.anotherCustomVariable = anotherCustomVariable;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.properties.value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@Component
@PropertySource("classpath:values.properties")
public class CollectionProvider {
private final List<String> values = new ArrayList<>();
public Collection<String> getValues() {
return Collections.unmodifiableCollection(values);
}
@Autowired
public void setValues(@Value("#{'${listOfValues}'.split(',')}") List<String> values) {
this.values.addAll(values);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.properties.value;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class InitializerBean {
private String someInitialValue;
private String anotherManagedValue;
public InitializerBean(@Value("someInitialValue") String someInitialValue, @Value("anotherValue") String anotherManagedValue) {
this.someInitialValue = someInitialValue;
this.anotherManagedValue = anotherManagedValue;
}
public ClassNotManagedBySpring initClass() {
return new ClassNotManagedBySpring(this.someInitialValue, this.anotherManagedValue);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.properties.value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:values.properties")
public class PriorityProvider {
private final String priority;
@Autowired
public PriorityProvider(@Value("${priority:normal}") String priority) {
this.priority = priority;
}
public String getPriority() {
return priority;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.properties.value;
public class SomeBean {
private int someValue;
public SomeBean(int someValue) {
this.someValue = someValue;
}
public int getSomeValue() {
return someValue;
}
public void setSomeValue(int someValue) {
this.someValue = someValue;
}
}

View File

@ -0,0 +1,101 @@
package com.baeldung.properties.value;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
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 javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Configuration
@PropertySource(name = "myProperties", value = "values.properties")
public class ValuesApp {
@Value("string value")
private String stringValue;
@Value("${value.from.file}")
private String valueFromFile;
@Value("${systemValue}")
private String systemValue;
@Value("${unknown_param:some default}")
private String someDefault;
@Value("${priority}")
private String prioritySystemProperty;
@Value("${listOfValues}")
private String[] valuesArray;
@Value("#{systemProperties['priority']}")
private String spelValue;
@Value("#{systemProperties['unknown'] ?: 'some default'}")
private String spelSomeDefault;
@Value("#{someBean.someValue}")
private Integer someBeanValue;
@Value("#{'${listOfValues}'.split(',')}")
private List<String> valuesList;
@Value("#{${valuesMap}}")
private Map<String, Integer> valuesMap;
@Value("#{${valuesMap}.key1}")
private Integer valuesMapKey1;
@Value("#{${valuesMap}['unknownKey']}")
private Integer unknownMapKey;
@Value("#{${unknownMap : {key1:'1', key2 : '2'}}}")
private Map<String, Integer> unknownMap;
@Value("#{${valuesMap}['unknownKey'] ?: 5}")
private Integer unknownMapKeyWithDefaultValue;
@Value("#{${valuesMap}.?[value>'1']}")
private Map<String, Integer> valuesMapFiltered;
@Value("#{systemProperties}")
private Map<String, String> systemPropertiesMap;
public static void main(String[] args) {
System.setProperty("systemValue", "Some system parameter value");
System.setProperty("priority", "System property");
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesApp.class);
}
@Bean
public SomeBean someBean() {
return new SomeBean(10);
}
@PostConstruct
public void afterInitialize() {
System.out.println(stringValue);
System.out.println(valueFromFile);
System.out.println(systemValue);
System.out.println(someDefault);
System.out.println(prioritySystemProperty);
System.out.println(Arrays.toString(valuesArray));
System.out.println(spelValue);
System.out.println(spelSomeDefault);
System.out.println(someBeanValue);
System.out.println(valuesList);
System.out.println(valuesMap);
System.out.println(valuesMapKey1);
System.out.println(unknownMapKey);
System.out.println(unknownMap);
System.out.println(unknownMapKeyWithDefaultValue);
System.out.println(valuesMapFiltered);
System.out.println(systemPropertiesMap);
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.properties.value.defaults;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.Assert;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
/**
* Demonstrates setting defaults for @Value annotation. Note that there are no properties
* defined in the specified property source. We also assume that the user here
* does not have a system property named some.key.
*
*/
@Configuration
@PropertySource(name = "myProperties", value = "valueswithdefaults.properties")
public class ValuesWithDefaultsApp {
@Value("${some.key:my default value}")
private String stringWithDefaultValue;
@Value("${some.key:}")
private String stringWithBlankDefaultValue;
@Value("${some.key:true}")
private boolean booleanWithDefaultValue;
@Value("${some.key:42}")
private int intWithDefaultValue;
@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;
@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;
@Value("#{systemProperties['some.key'] ?: 'my default system property value'}")
private String spelWithDefaultValue;
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class);
}
@PostConstruct
public void afterInitialize() {
// strings
Assert.isTrue(stringWithDefaultValue.equals("my default value"));
Assert.isTrue(stringWithBlankDefaultValue.equals(""));
// other primitives
Assert.isTrue(booleanWithDefaultValue);
Assert.isTrue(intWithDefaultValue == 42);
// arrays
List<String> stringListValues = Arrays.asList("one", "two", "three");
Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues));
List<Integer> intListValues = Arrays.asList(1, 2, 3);
Assert.isTrue(Arrays.asList(ArrayUtils.toObject(intArrayWithDefaults)).containsAll(intListValues));
// SpEL
Assert.isTrue(spelWithDefaultValue.equals("my default system property value"));
}
}

View File

@ -0,0 +1,4 @@
value.from.file=Value got from the file
priority=high
listOfValues=A,B,C
valuesMap={key1:'1', key2 : '2', key3 : '3'}

View File

@ -0,0 +1,40 @@
package com.baeldung.properties.value;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import static junit.framework.TestCase.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
public class ClassNotManagedBySpringIntegrationTest {
@MockBean
private InitializerBean initializerBean;
@Before
public void init() {
when(initializerBean.initClass())
.thenReturn(new ClassNotManagedBySpring("This is only sample value", "Another configured value"));
}
@Test
public void givenInitializerBean_whenInvokedInitClass_shouldInitialize() throws Exception {
//given
ClassNotManagedBySpring classNotManagedBySpring = initializerBean.initClass();
//when
String initializedValue = classNotManagedBySpring.getCustomVariable();
String anotherCustomVariable = classNotManagedBySpring.getAnotherCustomVariable();
//then
assertEquals("This is only sample value", initializedValue);
assertEquals("Another configured value", anotherCustomVariable);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.properties.value;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CollectionProvider.class)
public class CollectionProviderIntegrationTest {
@Autowired
private CollectionProvider collectionProvider;
@Test
public void givenPropertyFileWhenSetterInjectionUsedThenValueInjected() {
assertThat(collectionProvider.getValues()).contains("A", "B", "C");
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.properties.value;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PriorityProvider.class)
public class PriorityProviderIntegrationTest {
@Autowired
private PriorityProvider priorityProvider;
@Test
public void givenPropertyFileWhenConstructorInjectionUsedThenValueInjected() {
assertThat(priorityProvider.getPriority()).isEqualTo("high");
}
}

View File

@ -7,9 +7,6 @@ This module contains articles about Properties in Spring Boot.
- [Guide to @ConfigurationProperties in Spring Boot](https://www.baeldung.com/configuration-properties-in-spring-boot)
- [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties)
- [Properties with Spring and Spring Boot](https://www.baeldung.com/properties-with-spring) - checkout the `com.baeldung.properties` package for all scenarios of properties injection and usage
- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation)
- [Spring YAML Configuration](https://www.baeldung.com/spring-yaml)
- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults)
- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class)
- [Add Build Properties to a Spring Boot Application](https://www.baeldung.com/spring-boot-build-properties)
- [IntelliJ Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties)