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
https://docs.spring.io/spring-boot/docs/3.1.1/reference/html/configuration-metadata.html#appendix.configuration-metadata.annotation-processor