Spring SpEL - Annotation Based Configuration



SpEL expression can be used in Annotation based beans configuration

Syntax

Following is an example of using an expression in annotation based configuration.

@Value("#{ T(java.lang.Math).random() * 100.0 }")
private int id;

Here we are using @Value annotation and we've specified a SpEL expression on a property. Similarly we can specify SpEL expression on setter methods, on constructors and during autowiring as well.

@Value("#{ systemProperties['user.country'] }")
public void setCountry(String country) {
   this.country = country;
}

Following example shows the various use cases.

Example

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − An employee class.

  • AppConfig.java − A configuration class.

  • MainApp.java − Main application to run and test.

Here is the content of Employee.java file −

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Employee {
   @Value("#{ T(java.lang.Math).random() * 100.0 }")
   private int id;
   private String name;	
   private String country;

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   @Value("Mahesh")
   public void setName(String name) {
      this.name = name;
   }
   public String getCountry() {
      return country;
   }
   @Value("#{ systemProperties['user.country'] }")
   public void setCountry(String country) {
      this.country = country;
   }
   @Override
   public String toString() {
      return "[" + id + ", " + name + ", " + country + "]";
   }
}

Here is the content of AppConfig.java file −

package com.tutorialspoint;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.tutorialspoint")
public class AppConfig {
}

Here is the content of MainApp.java file −

package com.tutorialspoint;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
      context.register(AppConfig.class);
      context.refresh();

      Employee emp = context.getBean(Employee.class);
      System.out.println(emp);	   
   }
}

Output

[84, Mahesh, IN]
Advertisements