BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
@@ -0,0 +1,124 @@
package com.baeldung.configurationproperties;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.validation.annotation.Validated;
@Configuration
@PropertySource("classpath:configprops.properties")
@ConfigurationProperties(prefix = "mail")
@Validated
public class ConfigProperties {
@Validated
public static class Credentials {
@Length(max = 4, min = 1)
private String authMethod;
private String username;
private String password;
public String getAuthMethod() {
return authMethod;
}
public void setAuthMethod(String authMethod) {
this.authMethod = authMethod;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@NotBlank
private String hostName;
@Min(1025)
@Max(65536)
private int port;
@Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$")
private String from;
private Credentials credentials;
private List<String> defaultRecipients;
private Map<String, String> additionalHeaders;
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
public List<String> getDefaultRecipients() {
return defaultRecipients;
}
public void setDefaultRecipients(List<String> defaultRecipients) {
this.defaultRecipients = defaultRecipients;
}
public Map<String, String> getAdditionalHeaders() {
return additionalHeaders;
}
public void setAdditionalHeaders(Map<String, String> additionalHeaders) {
this.additionalHeaders = additionalHeaders;
}
@Bean
@ConfigurationProperties(prefix = "item")
public Item item(){
return new Item();
}
}
@@ -0,0 +1,30 @@
package com.baeldung.configurationproperties;
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.configurationproperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
@ConfigurationPropertiesBinding
public class EmployeeConverter implements Converter<String, Employee> {
@Override
public Employee convert(String from) {
String[] data = from.split(",");
return new Employee(data[0], Double.parseDouble(data[1]));
}
}
@@ -0,0 +1,31 @@
package com.baeldung.configurationproperties;
public class Item {
private String name;
private int size;
public Item() {
}
public Item(String name, int size) {
this.name = name;
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.configurationproperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackageClasses = { PropertyConversion.class, EmployeeConverter.class })
public class PropertiesConversionApplication {
public static void main(String[] args) {
SpringApplication.run(PropertiesConversionApplication.class, args);
}
}
@@ -0,0 +1,92 @@
package com.baeldung.configurationproperties;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.convert.DataSizeUnit;
import org.springframework.boot.convert.DurationUnit;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;
@Configuration
@PropertySource("classpath:conversion.properties")
@ConfigurationProperties(prefix = "conversion")
public class PropertyConversion {
private Duration timeInDefaultUnit;
private Duration timeInNano;
@DurationUnit(ChronoUnit.DAYS)
private Duration timeInDays;
private DataSize sizeInDefaultUnit;
private DataSize sizeInGB;
@DataSizeUnit(DataUnit.TERABYTES)
private DataSize sizeInTB;
private Employee employee;
// Getters and setters
public Duration getTimeInDefaultUnit() {
return timeInDefaultUnit;
}
public void setTimeInDefaultUnit(Duration timeInDefaultUnit) {
this.timeInDefaultUnit = timeInDefaultUnit;
}
public Duration getTimeInNano() {
return timeInNano;
}
public void setTimeInNano(Duration timeInNano) {
this.timeInNano = timeInNano;
}
public Duration getTimeInDays() {
return timeInDays;
}
public void setTimeInDays(Duration timeInDays) {
this.timeInDays = timeInDays;
}
public DataSize getSizeInDefaultUnit() {
return sizeInDefaultUnit;
}
public void setSizeInDefaultUnit(DataSize sizeInDefaultUnit) {
this.sizeInDefaultUnit = sizeInDefaultUnit;
}
public DataSize getSizeInGB() {
return sizeInGB;
}
public void setSizeInGB(DataSize sizeInGB) {
this.sizeInGB = sizeInGB;
}
public DataSize getSizeInTB() {
return sizeInTB;
}
public void setSizeInTB(DataSize sizeInTB) {
this.sizeInTB = sizeInTB;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(AdditionalProperties.class)
public class AdditionalConfiguration {
@Autowired
private AdditionalProperties additionalProperties;
}
@@ -0,0 +1,28 @@
package com.baeldung.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "additional")
public class AdditionalProperties {
private String unit;
private int max;
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.properties;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.ComponentScan;
import com.baeldung.configurationproperties.ConfigProperties;
@SpringBootApplication
@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class })
public class ConfigPropertiesDemoApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer())
.run();
}
}
@@ -0,0 +1,71 @@
package com.baeldung.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "custom")
public class CustomJsonProperties {
private String host;
private int port;
private boolean resend;
private Person sender;
public static class Person {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isResend() {
return resend;
}
public void setResend(boolean resend) {
this.resend = resend;
}
public Person getSender() {
return sender;
}
public void setSender(Person sender) {
this.sender = sender;
}
}
@@ -0,0 +1,64 @@
package com.baeldung.properties;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class)
@ConfigurationProperties
public class JsonProperties {
private String host;
private int port;
private boolean resend;
private List<String> topics;
private LinkedHashMap<String, ?> sender;
public LinkedHashMap<String, ?> getSender() {
return sender;
}
public void setSender(LinkedHashMap<String, ?> sender) {
this.sender = sender;
}
public List<String> getTopics() {
return topics;
}
public void setTopics(List<String> topics) {
this.topics = topics;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isResend() {
return resend;
}
public void setResend(boolean resend) {
this.resend = resend;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
@@ -0,0 +1,68 @@
package com.baeldung.properties;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonPropertyContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private final static String CUSTOM_PREFIX = "custom.";
@Override
@SuppressWarnings("unchecked")
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
try {
Resource resource = configurableApplicationContext.getResource("classpath:configprops.json");
Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
Set<Map.Entry> set = readValue.entrySet();
List<MapPropertySource> propertySources = convertEntrySet(set, Optional.empty());
for (PropertySource propertySource : propertySources) {
configurableApplicationContext.getEnvironment()
.getPropertySources()
.addFirst(propertySource);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static List<MapPropertySource> convertEntrySet(Set<Map.Entry> entrySet, Optional<String> parentKey) {
return entrySet.stream()
.map((Map.Entry e) -> convertToPropertySourceList(e, parentKey))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
private static List<MapPropertySource> convertToPropertySourceList(Map.Entry e, Optional<String> parentKey) {
String key = parentKey.map(s -> s + ".")
.orElse("") + (String) e.getKey();
Object value = e.getValue();
return covertToPropertySourceList(key, value);
}
@SuppressWarnings("unchecked")
private static List<MapPropertySource> covertToPropertySourceList(String key, Object value) {
if (value instanceof LinkedHashMap) {
LinkedHashMap map = (LinkedHashMap) value;
Set<Map.Entry> entrySet = map.entrySet();
return convertEntrySet(entrySet, Optional.ofNullable(key));
}
String finalKey = CUSTOM_PREFIX + key;
return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value)));
}
}
@@ -0,0 +1,21 @@
package com.baeldung.properties;
import java.io.IOException;
import java.util.Map;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
return new MapPropertySource("json-property", readValue);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.properties.core;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
public class ComponentInXmlUsingProperties implements InitializingBean {
@Autowired
private Environment env;
@Value("${key.something}")
private String injectedProperty;
public ComponentInXmlUsingProperties(final String propertyValue) {
super();
System.out.println("Constructor Injection - Property Value resolved to: " + propertyValue);
}
//
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("in afterPropertiesSet via @Value: " + injectedProperty);
System.out.println("in afterPropertiesSet Environment: " + env.getProperty("key.something"));
}
}
@@ -0,0 +1,30 @@
package com.baeldung.properties.core;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class ComponentUsingProperties implements InitializingBean {
@Autowired
private Environment env;
@Value("${key.something}")
private String injectedProperty;
public ComponentUsingProperties() {
super();
}
//
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("in afterPropertiesSet via @Value: " + injectedProperty);
System.out.println("in afterPropertiesSet Environment: " + env.getProperty("key.something"));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.properties.external;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@ComponentScan("org.baeldung.properties.core")
@PropertySource("classpath:foo.properties")
public class ExternalPropertiesWithJavaConfig {
public ExternalPropertiesWithJavaConfig() {
super();
}
// beans
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@@ -0,0 +1,16 @@
package com.baeldung.properties.external;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource("classpath:configForProperties.xml")
@ComponentScan("org.baeldung.core")
public class ExternalPropertiesWithXmlConfig {
public ExternalPropertiesWithXmlConfig() {
super();
}
}
@@ -0,0 +1,16 @@
package com.baeldung.properties.external;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource("classpath:configForPropertiesOne.xml")
@ComponentScan("org.baeldung.core")
public class ExternalPropertiesWithXmlConfigOne {
public ExternalPropertiesWithXmlConfigOne() {
super();
}
}
@@ -0,0 +1,14 @@
package com.baeldung.properties.external;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource("classpath:basicConfigForPropertiesTwo.xml")
public class ExternalPropertiesWithXmlConfigTwo {
public ExternalPropertiesWithXmlConfigTwo() {
super();
}
}
@@ -0,0 +1,44 @@
package com.baeldung.properties.reloading;
import com.baeldung.properties.reloading.configs.ReloadableProperties;
import java.io.File;
import java.util.Properties;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
@SpringBootApplication
public class SpringBootPropertiesApplication {
@Bean
@ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false)
public PropertiesConfiguration propertiesConfiguration(
@Value("${spring.config.location}") String path,
@Value("${spring.properties.refreshDelay}") long refreshDelay) throws Exception {
String filePath = path.substring("file:".length());
PropertiesConfiguration configuration = new PropertiesConfiguration(new File(filePath).getCanonicalPath());
FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy();
fileChangedReloadingStrategy.setRefreshDelay(refreshDelay);
configuration.setReloadingStrategy(fileChangedReloadingStrategy);
return configuration;
}
@Bean
@ConditionalOnBean(PropertiesConfiguration.class)
@Primary
public Properties properties(PropertiesConfiguration propertiesConfiguration) throws Exception {
ReloadableProperties properties = new ReloadableProperties(propertiesConfiguration);
return properties;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootPropertiesApplication.class, args);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.properties.reloading.configs;
public class PropertiesException extends RuntimeException {
public PropertiesException() {
}
public PropertiesException(Throwable cause) {
super(cause);
}
}
@@ -0,0 +1,49 @@
package com.baeldung.properties.reloading.configs;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;
import javax.naming.OperationNotSupportedException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class ReloadableProperties extends Properties {
private PropertiesConfiguration propertiesConfiguration;
public ReloadableProperties(PropertiesConfiguration propertiesConfiguration) throws IOException {
super.load(new FileReader(propertiesConfiguration.getFile()));
this.propertiesConfiguration = propertiesConfiguration;
}
@Override
public synchronized Object setProperty(String key, String value) {
propertiesConfiguration.setProperty(key, value);
return super.setProperty(key, value);
}
@Override
public String getProperty(String key) {
String val = propertiesConfiguration.getString(key);
super.setProperty(key, val);
return val;
}
@Override
public String getProperty(String key, String defaultValue) {
String val = propertiesConfiguration.getString(key, defaultValue);
super.setProperty(key, val);
return val;
}
@Override
public synchronized void load(Reader reader) throws IOException {
throw new PropertiesException(new OperationNotSupportedException());
}
@Override
public synchronized void load(InputStream inStream) throws IOException {
throw new PropertiesException(new OperationNotSupportedException());
}
}
@@ -0,0 +1,33 @@
package com.baeldung.properties.reloading.configs;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils;
public class ReloadablePropertySource extends PropertySource {
PropertiesConfiguration propertiesConfiguration;
public ReloadablePropertySource(String name, PropertiesConfiguration propertiesConfiguration) {
super(name);
this.propertiesConfiguration = propertiesConfiguration;
}
public ReloadablePropertySource(String name, String path) {
super(StringUtils.isEmpty(name) ? path : name);
try {
this.propertiesConfiguration = new PropertiesConfiguration(path);
FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
strategy.setRefreshDelay(1000);
this.propertiesConfiguration.setReloadingStrategy(strategy);
} catch (Exception e) {
throw new PropertiesException(e);
}
}
@Override
public Object getProperty(String s) {
return propertiesConfiguration.getProperty(s);
}
}
@@ -0,0 +1,29 @@
package com.baeldung.properties.reloading.configs;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
@Configuration
public class ReloadablePropertySourceConfig {
private ConfigurableEnvironment env;
public ReloadablePropertySourceConfig(@Autowired ConfigurableEnvironment env) {
this.env = env;
}
@Bean
@ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false)
public ReloadablePropertySource reloadablePropertySource(PropertiesConfiguration properties) {
ReloadablePropertySource ret = new ReloadablePropertySource("dynamic", properties);
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(ret);
return ret;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.properties.reloading.configs;
import java.io.IOException;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.FileUrlResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
public class ReloadablePropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
Resource internal = encodedResource.getResource();
if (internal instanceof FileSystemResource) {
return new ReloadablePropertySource(s, ((FileSystemResource) internal).getPath());
}
if (internal instanceof FileUrlResource) {
return new ReloadablePropertySource(s, ((FileUrlResource) internal)
.getURL()
.getPath());
}
return super.createPropertySource(s, encodedResource);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.properties.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:foo.properties")
public class BasicPropertiesWithJavaConfig {
public BasicPropertiesWithJavaConfig() {
super();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.properties.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:foo.properties")
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfig {
public PropertiesWithJavaConfig() {
super();
}
// beans
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@@ -0,0 +1,16 @@
package com.baeldung.properties.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfigOther {
public PropertiesWithJavaConfigOther() {
super();
}
// beans
}
@@ -0,0 +1,21 @@
package com.baeldung.properties.spring;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PropertiesWithPlaceHolderConfigurer {
public PropertiesWithPlaceHolderConfigurer() {
super();
}
@Bean
public PropertyPlaceholderConfigurer propertyConfigurer() {
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
props.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK);
return props;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.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);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.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;
}
}
@@ -0,0 +1,102 @@
package com.baeldung.value;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
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;
@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);
}
}
@@ -0,0 +1,75 @@
package com.baeldung.valuewithdefaults;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
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 com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
/**
* 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 = Lists.newArrayList("one", "two", "three");
Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues));
List<Integer> intListValues = Lists.newArrayList(1, 2, 3);
Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues));
// SpEL
Assert.isTrue(spelWithDefaultValue.equals("my default system property value"));
}
}
@@ -0,0 +1,31 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.yaml;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication implements CommandLineRunner {
@Autowired
private YAMLConfig myConfig;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MyApplication.class);
app.run();
}
public void run(String... args) throws Exception {
System.out.println("using environment:" + myConfig.getEnvironment());
System.out.println("name:" + myConfig.getName());
System.out.println("servers:" + myConfig.getServers());
}
}
@@ -0,0 +1,41 @@
package com.baeldung.yaml;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YAMLConfig {
private String name;
private String environment;
private List<String> servers = new ArrayList<String>();
public List<String> getServers() {
return servers;
}
public void setServers(List<String> servers) {
this.servers = servers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
}
@@ -0,0 +1,4 @@
management.endpoints.web.exposure.include=refresh
spring.properties.refreshDelay=1000
spring.config.location=file:extra.properties
spring.main.allow-bean-definition-overriding=true
@@ -0,0 +1,17 @@
spring:
profiles: test
name: test-YAML
environment: test
servers:
- www.abc.test.com
- www.xyz.test.com
---
spring:
profiles: prod
name: prod-YAML
environment: production
servers:
- www.abc.com
- www.xyz.com
@@ -0,0 +1 @@
key.something2=val2
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:foo.properties"/>
</beans>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:foo.properties" ignore-unresolvable="true" order="1"/>
</beans>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:property-placeholder location="classpath:bar.properties"
order="2" />
</beans>
@@ -0,0 +1 @@
child.name=child
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:foo.properties,classpath:bar.properties"/>
<bean id="componentInXmlUsingProperties" class="com.baeldung.properties.core.ComponentInXmlUsingProperties">
<constructor-arg value="${key.something}"/>
</bean>
</beans>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:foo.properties" ignore-unresolvable="true" order="1"/>
<bean id="componentInXmlUsingProperties" class="com.baeldung.properties.core.ComponentInXmlUsingProperties">
<constructor-arg value="${key.something2}"/>
</bean>
</beans>
@@ -0,0 +1,10 @@
{
"host" : "mailer@mail.com",
"port" : 9090,
"resend" : true,
"topics" : ["spring", "boot"],
"sender" : {
"name": "sender",
"address": "street"
}
}
@@ -0,0 +1,27 @@
#Simple properties
mail.hostname=host@mail.com
mail.port=9000
mail.from=mailer@mail.com
#List properties
mail.defaultRecipients[0]=admin@mail.com
mail.defaultRecipients[1]=owner@mail.com
#Map Properties
mail.additionalHeaders.redelivery=true
mail.additionalHeaders.secure=true
mail.additionalHeaders.p3=value
#Object properties
mail.credentials.username=john
mail.credentials.password=password
mail.credentials.authMethod=SHA1
#Bean method properties
item.name=Item name
item.size=42
#Additional properties
additional.unit=km
additional.max=100
@@ -0,0 +1,2 @@
conversion.timeInDefaultUnit=10
conversion.timeInNano=9ns
@@ -0,0 +1 @@
key.something=val
@@ -0,0 +1 @@
parent.name=parent
@@ -0,0 +1,4 @@
value.from.file=Value got from the file
priority=Properties file
listOfValues=A,B,C
valuesMap={key1:'1', key2 : '2', key3 : '3'}