Home  >  Spring Core

Example of @PropertySource in Spring

By Arvind Rai, March 12, 2013
@PropertySource in spring can read the values from property file. @PropertySource is annotation based and we need to provide the config file path. With the help of org.springframework.core.env.Environment , the values is read. See below to use @PropertySource
@PropertySource("classpath:prop.cfg")
public class Config {}

 
@PropertySource is applied on class level. Find the complete example for @PropertySource in spring.

prop.cfg
prop.name=Ankita
prop.age=18
 





Person.java
package com.concretepage;
public class Person {
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
 


Config.java
package com.concretepage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:prop.cfg")
public class Config {
	@Autowired
    Environment env;
	
	@Bean
    public Person person() {
        Person person= new Person();
        person.setName(env.getProperty("prop.name"));
        person.setAge(Integer.parseInt(env.getProperty("prop.age"))); 
        return person;
    }
}
 


PropertySourceTest.java
package com.concretepage;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class PropertySourceTest {
	public static void main(String[] args) {
		  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		   
	      ctx.register(Config.class);
	      ctx.refresh();
	
	      Person person = ctx.getBean(Person.class);
	      
	      System.out.println(person.getName());
	      System.out.println(person.getAge());
	}
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us