Home  >  Spring Core

Example of @Value in Spring

By Arvind Rai, April 06, 2013
@Value is used with @Configuration. @Value reads the property file. Property file can be loaded by application xml and that xml provides the utill properties. In our example we get the util property from application xml and then import that xml file in our @Configuration file and reads the property by @Value.

AppConfig.java
package com.concretepage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:/app-conf.xml")
public class AppConfig  {
    private @Value("#{entProp['entitlement.name']}") String entName;
    private @Value("#{entProp['entitlement.time']}") int entTime;
 
	@Bean(name="entitlement")
	public Entitlement entitlement(){
		Entitlement ent= new Entitlement();
		ent.setName(entName);
		ent.setTime(entTime);
		return ent;
	}

}
 


app-conf.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
     
    <util:properties id="entProp" location="classpath:/entitlement.cfg" />
    
</beans>
 


Entitlement.java
package com.concretepage;

public class Entitlement {
	private String name;
	private int time;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getTime() {
		return time;
	}
	public void setTime(int time) {
		this.time = time;
	}
}
 


entitlement.cfg
entitlement.name= Entitlement
entitlement.time= 10
 


package com.concretepage;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppTest {
	public static void main(String[] args) throws SQLException {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
 
		ctx.register(AppConfig.class);
		ctx.refresh();

		Entitlement ent= (Entitlement)ctx.getBean("entitlement");
	    System.out.println(ent.getName());		
	    System.out.println(ent.getTime());
	}
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us