Suppose I have a POJO called Address, I’d like to load external resource data and replace the address line1 and line2 value.
public class Address { private String addressline1; private String addressline2; // getter and setter }
address.properties
address.line1= 123 Abc Condominium, address.line2= Street 123456
Partition Application Context
Now i partition the application context into AppConfig and InfraConfig, and I’ll show 2 approach on how to do it.
InfraConfig.java
@Configuration @PropertySource("classpath:address.properties") public class InfraConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
First Approach – AppConfig.java
@Configuration @Import(InfraConfig.class) public class AppConfig { @Value("${address.line1}") private String addressline1; @Value("${address.line2}") private String addressline2; @Bean public Address address() { Address address = new Address(); address.setAddressline1(addressline1); address.setAddressline2(addressline2); return address; } }
Create a client code to run.
public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); Address address = ctx.getBean(Address.class); System.out.println(address.getAddressline1()); System.out.println(address.getAddressline2()); }
Alternative – Use Environment
Second Approach – AppConfig.java
@Configuration @Import(InfraConfig.class) public class AppConfig { @Autowired private Environment env; @Bean public Address address() { Address address = new Address(); address.setAddressline1(env.getProperty("address.line1")); address.setAddressline2(env.getProperty("address.line2")); return address; } }
JavaConfig – SpringExpL