English 中文(简体)
Spring SpEL - Annotation Configuration
  • 时间:2024-09-17

Spring SpEL - Annotation Based Configuration


Previous Page Next Page  

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 ] }")
pubpc 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 apppcation 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
pubpc class Employee {
   @Value("#{ T(java.lang.Math).random() * 100.0 }")
   private int id;
   private String name;	
   private String country;

   pubpc int getId() {
      return id;
   }
   pubpc void setId(int id) {
      this.id = id;
   }
   pubpc String getName() {
      return name;
   }
   @Value("Mahesh")
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc String getCountry() {
      return country;
   }
   @Value("#{ systemProperties[ user.country ] }")
   pubpc void setCountry(String country) {
      this.country = country;
   }
   @Override
   pubpc 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")
pubpc class AppConfig {
}

Here is the content of MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.annotation.AnnotationConfigApppcationContext;

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

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

Output


[84, Mahesh, IN]
Advertisements