-
Springboot, 주입한 환경변수 사용하기Spring Boot/환경설정 2023. 6. 30. 23:09
외부 환경변수 주입 방법과 우선 순위 : https://yeoon.tistory.com/115
Spring Boot, 환경 변수 주입 우선순위
스프링에서 환경변수는 외부에서 주입할 수 있다. 주입 받은 환경 변수는 @Value 어노테이션을 사용하여 빈에 주입하거나, @ConfigurationProperties를 사용하여 바인딩 할 수 있다. 환경변수를 주입은
yeoon.tistory.com
1. Environment 인터페이스 사용하기
import org.springframework.core.env.Environment; @Controller public class TodoController { private Environment env; public TodoController(Environment env) { this.env = env; } @RequestMapping("/todos") public ModelAndView todos() throws Exception { SiteProperties site = new SiteProperties(); site.setAuthor(env.getProperty("site.author")); site.setDescription(env.getProperty("site.description")); ModelAndView mav = new ModelAndView(); mav.addObject("site", site); mav.setViewName("todos"); return mav; } }
2. @Value 사용하기
import org.springframework.core.env.Environment; @Controller public class TodoController { @Value("${site.author}") String author; @Value("${site.description}") String description; @RequestMapping("/todos") public ModelAndView todos() throws Exception { SiteProperties site = new SiteProperties(); site.setAuthor(author); site.setDescription(description)); ModelAndView mav = new ModelAndView(); mav.addObject("site", site); mav.setViewName("todos"); return mav; } }
3. ConfigurationProperties 사용
- prefix와 멤버변수를 읽어서 자동으로 환경변수를 읽는다.
- @ConfigurationPropertiesScan이라는 애노테이션이 패키지를 탐색해서 @ConfigurationProperties가 선언된 클래스가 있으면 Bean으로 자동 등록한다.
@ConfigurationProperties(prefix = "site") public class SiteProperties { private String author = "unknown"; private String description = "TodoApp templates for Server-side"; } @Controller public class TodoController { private final SiteProperties siteProperties; public TodoController(SiteProperties siteProperties) { this.siteProperties = siteProperties; } @RequestMapping("/todos") public ModelAndView todos() throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("site", siteProperties); mav.setViewName("todos"); return mav; } } @SpringBootApplication @ConfigurationPropertiesScan public class TodosApplication { public static void main(String[] args) { SpringApplication.run(TodosApplication.class, args); } }
Reference
반응형'Spring Boot > 환경설정' 카테고리의 다른 글
[springboot] Datasource Proxy로 SQL query logging 하기 (3) 2024.01.11 artillery로 부하테스트 하기 (0) 2023.10.29 [docker] docker compose로 데이터베이스 한번에 N개 띄우기 (0) 2023.10.23 [IntelliJ] Java Google Code Style 적용하기 (0) 2023.06.10 Spring Boot, 환경 변수 주입 우선순위 (0) 2023.06.03