@value annotation is used to bind default values to java bean. This example tutorial will cover how to use @Value with Spring EL.

Syntax:

#{...}

Property file : env.properties

jdbc.url=127.0.0.1
jdbc.userid=
jdbc.userid.default=admin
jdbc.port=1521

1. Using SpringEL with @Value in JavaConfig


1.1 Define PropertySourcesPlaceholderConfigurer as bean in @Configuration annotated class.


DatabaseConfigBean.java:

	@Bean
	public PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
		return new PropertySourcesPlaceholderConfigurer();
	}

1.2 Use @PropertySource annotation, to load the property file.


Following sample code uses @PropertySource and scans spring beans which are annotated with @Component annotation in the specified package.

package com.codesimplify.config;
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(basePackages = {"com.codesimplify.config.beans"})
@PropertySource("classpath:env.properties")
public class SampleConfig {    
	@Bean
	public PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
		return new PropertySourcesPlaceholderConfigurer();
	}
}

1.3 Use @Value annotation with SpringEL(‘#’).


Annotate Spring bean field with @value annotation

	@Value("#{'${jdbc.url}'}")
	private String dbUrl;

In the above code, @Value will be evaluated to set the field with property value for key “jdbc.url”.

NOTE: When using property placeholder with Spring EL, use following Syntax.
#{ ‘ ${..}’ }

1.4 Run the application

package com.codesimplify;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.codesimplify.config.AppConfig;
import com.codesimplify.config.beans.DatabaseConfigBean;

public class ValueAnnotationUsageApp {

	public static void main(String[] args) {		
			    
		  ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
		  DatabaseConfigBean dbConfigBean = (Da-tabaseConfigBean) context.getBean("dbConfigBean");
			    
		 System.out.println("DB URL:"+ dbConfigBean.getDbUrl() );
	 
	}
}

Output:

DB URL:127.0.0.1

2. Using Spring EL in XML configuration


2.1 Create simple Java bean to set properties to it.

package com.codesimplify.config.beans;

public class DbXMLConfigBean {

	private String dbUrl;
	private String dbUserId;
	private int port;
	
	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getDbUrl() {
		return dbUrl;
	}

	public void setDbUrl(String dbUrl) {
		this.dbUrl = dbUrl;
	}

	public String getDbUserId() {
		return dbUserId;
	}

	public void setDbUserId(String dbUserId) {
		this.dbUserId = dbUserId;
	}

}

2.2 XML configuration to set the bean


Following XML configuration loads property file and sets the properties to spring bean using SpringEL.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
	    <property name="ignoreUnresolvablePlaceholders" value="true" />
	    <property name="locations">
	        <list>
	            <value>classpath:env.properties</value>
	        </list>
	    </property>
	    
	</bean>
	<bean name="dbConfigBean" class="com.codesimplify.config.beans.DatabaseConfigBean">
	  <property name="dbUrl" value="#{'${jdbc.url}'}" />
	  <property name="dbUserId" value="#{'${jdbc.userid}'?:'admin'}" />
      <property name="port" value="#{T(java.lang.Integer).parseInt('${jdbc.port}')}" /> 
	</bean>
</beans>

If we observe the above XML configuration, we can see SpringEL usage in various ways.

  • #{expression?:defaultExression} : Since no value is set for ‘jdbc.userid’ property, default Expression is evaluated.
  • #{T(java.lang.Integer).parseInt(‘${jdbc.port}’)}: We used Spring EL to convert string representation of property value into integer.

2.3 Run the application.

ValueAnnotationUsageXmlConfig.java
package com.codesimplify;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.codesimplify.config.beans.DatabaseConfigBean;

public class ValueAnnotationUsageXmlConfig {

	public static void main(String[] args) {		
			    
		  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		  DatabaseConfigBean dbConfigBean = (DatabaseConfigBean) context.getBean("dbConfigBean");
			    
		 System.out.println("DB URL:"+ dbConfigBean.getDbUrl() );
		 System.out.println("DB UserId:"+ dbConfigBean.getDbUserId() );	
		 System.out.println("DB Port:"+ dbConfigBean.getPort() );	
	}
}

Output:
DB URL:127.0.0.1
DB UserId:admin
DB Port:1521

References


Spring EL Guide

Spring @Value usage using SpringEL
Tagged on:         

2 thoughts on “Spring @Value usage using SpringEL

Leave a Reply

Your email address will not be published. Required fields are marked *