Spring-boot读书笔记一SpEL

SpEL (Spring Expression Language) is a powerful expression language that supports querying and manipulating objects at runtime in Spring applications.

Basic Syntax:
SpEL expressions are enclosed in #{} or ${}:
1,#{} - SpEL expressions
2,${} - Property placeholders

Common SpEL Features:
1. Literal Values:

@Value("#{42}")
private int number;

@Value("#{'Hello World'}")
private String text;

@Value("#{true}")
private boolean flag;

2. Property Access:

@Value("#{systemProperties['user.home']}")
private String userHome;

@Value("#{environment['server.port']}")
private String serverPort;

3. Method Invocation:

@Value("#{'Hello'.toUpperCase()}")
private String upperCase;

@Value("#{T(java.lang.Math).random()}")
private double randomValue;

4. Bean References:

@Value("#{courseService.findAllCourses().size()}")
private int courseCount;

@Value("#{@courseService.getTotalCourses()}")
private int totalCourses;

5. Conditional Expressions:
@Value("#{user.age >= 18 ? 'Adult' : 'Minor'}")
private String ageCategory;

@Value("#{user.name ?: 'Anonymous'}")
private String userName;

Spring Security SpEL:
Method Security:

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser() { }

@PreAuthorize("hasRole('USER') and #username == authentication.name")
public User getUser(String username) { }

@PostAuthorize("returnObject.owner == authentication.name")
public Document getDocument(Long id) { }

Web Security:

http.authorizeHttpRequests(auth -> auth
    .requestMatchers("/admin/**").access("hasRole('ADMIN')")
    .requestMatchers("/user/**").access("hasRole('USER') and #request.remoteAddr == '127.0.0.1'")
);

Built-in Variables:

  • authentication - Current authentication object
  • principal - Current user principal
  • request - HTTP request object
  • response - HTTP response object
  • session - HTTP session

Operators:
Arithmetic:

@Value("#{10 + 5}")  // Addition
@Value("#{10 - 5}")  // Subtraction
@Value("#{10 * 5}")  // Multiplication
@Value("#{10 / 5}")  // Division
@Value("#{10 % 3}")  // Modulus

Comparison:

@Value("#{10 > 5}")   // Greater than
@Value("#{10 < 5}")   // Less than
@Value("#{10 == 5}")  // Equal
@Value("#{10 != 5}")  // Not equal

Logical:

@Value("#{true and false}")  // AND
@Value("#{true or false}")   // OR
@Value("#{!true}")           // NOT

Collection Operations:

@Value("#{users.?[age > 18]}")  // Filter
private List<User> adults;

@Value("#{users.![name]}")      // Projection
private List<String> names;

@Value("#{users.^[age > 18]}")  // First match
private User firstAdult;

Use Cases:

  • Configuration values with dynamic evaluation
  • Security expressions for access control
  • Conditional bean creation
  • Dynamic property injection
  • Template expressions in annotations

SpEL provides flexible runtime expression evaluation, making Spring applications more dynamic and configurable.

posted @ 2026-01-07 13:29  kkbln  阅读(1)  评论(0)    收藏  举报