-
[SPRING] SPEL 스프링 표현식Spring/spring framework 기본 및 이론 2021. 2. 8. 18:17
스프링 EL(Expression Language) 란 객체 그래프를 조회하고 조작하는 기능을 제공하는 언어를 말한다.
spEL은 모든 스프링 프로젝트에서 사용하는 expression language로 만들었다.
문법이나 규칙은 배우기가 쉽다.
-
#{"표현식"}
-
${"프로퍼티"}
-
이런식으로 특정 객체를 가져와서 문자열처럼 사용할 수 있고, 계산도 할 수 있다. 표현식은 프로퍼티를 포함할 수 있지만, 반대로는 불가능하다.
사용처
- @Value 애노테이션 안에 spEL을 쓰면, 아래 필드값에 결과가 주입된다.
- 스프링 시큐리티의 경우 메소드 시큐리티, @PreAuthorize, @PostAuthorize, @PreFilter, @PostFilter, XML 인터셉터 URL 설정 등에 사용된다.
- 스프렝 데이터에서 @Query 에 사용된다.
- 화면을 만드는 템플릿엔진인 타임리프(thymeleaf) 등에서도 사용된다.
예시
@Value("#{1 + 1}") int value; @Value("#{'안녕 ' + 'red'}") String greeting; @Value("#{1 eq 1}") boolean yn; @Value("red") String red; // application.properties (프로퍼티) 에서 blue.value 변수를 가져온다. @Value("${blue.value}") int blueValue; // Sample 객체의 data 필드 값을 가져온다. @Value("#{sample.data}") int sampleData;
사용 종류
Default Value
@Value("${car.type:Sedan}") private String type; // yml 에 값이 없으면 Sedan 로 default value 설정
System Variables
@Value("${user.name}") // Or @Value("${username}") private String userName; @Value("${number.of.processors}") // Or @Value("${number_of_processors}") private int numberOfProcessors; @Value("${java.home}") private String java;
Parameter Method Value
@Value("${car.brand}") public CarData setCarData(@Value("${car.color}") String color, String brand) { carData.setCarColor(color); carData.setCarBrand(brand); }
systemProperties
@Value("#{systemProperties['user.name']}") private String userName;
@Value("#{systemProperties}") private Map<String, String> properties;
public Driver(@Value("#{systemProperties['user.name']}") String name, String location) { this.name = name; this.location = location; }
Injecting into Maps
student.hobbies={indoor: 'reading, drawing', outdoor: 'fishing, hiking, bushcraft'}
@Value("#{${student.hobbies}}") private Map<String, List<String>> hobbies;
반응형'Spring > spring framework 기본 및 이론' 카테고리의 다른 글
[Spring] 스프링 어플리케이션 kill 시키기 (0) 2020.09.27 [SPRING] mockMvc 유닛 테스트 (0) 2020.06.16 [Spring] 스프링 mybatis transactions (0) 2020.06.02 [Spring] 스프링 mapper 등록하기 (0) 2020.06.02 [Spring] Mybatis SqlSessionFactory 란 (0) 2020.06.01 -