↗ JetBrains 20% discount
Buy any product from JetBrains and get a 20% discount.
In this tutorial we will see how to add user properties to Spring Environment using @PropertySource.
Environment
@PropertySource
@PropertySource annotation is used on @Configuration classes.
package org.springframework.context.annotation; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Repeatable(PropertySources.class) public @interface PropertySource { String name() default ""; 1 String[] value(); 2 boolean ignoreResourceNotFound() default false; 3 String encoding() default ""; 4 Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class; 5 }
#value
PropertySourceFactory
contact-person=Monica J. Pace
package com.logicbig.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.ConfigurableEnvironment; @Configuration @PropertySource("classpath:app.properties") public class UserPropertySourceExample { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(UserPropertySourceExample.class); ConfigurableEnvironment env = context.getEnvironment(); System.out.println("property sources:" + env.getPropertySources()); String contactPerson = env.getProperty("contact-person"); System.out.println("contact-person: " + contactPerson); } }
property sources:[PropertiesPropertySource {name='systemProperties'}, SystemEnvironmentPropertySource {name='systemEnvironment'}, ResourcePropertySource {name='class path resource [app.properties]'}]contact-person: Monica J. Pace
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.