๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Spring

์Šคํ”„๋ง ๋ถ€ํŠธ์—์„œ ์ฆ‰์‹œ ์›น ๊ฐœ๋ฐœ์„ ์‹œ์ž‘ํ•  ์ˆ˜ ์žˆ๋Š” ์ด์œ  - AutoConfiguration

by Leica 2020. 8. 19.
๋ฐ˜์‘ํ˜•

์Šคํ”„๋ง ๋ถ€ํŠธ์—์„œ ์ฆ‰์‹œ ์›น ๊ฐœ๋ฐœ์„ ์‹œ์ž‘ํ•  ์ˆ˜ ์žˆ๋Š” ์ด์œ  - AutoConfiguration

spring-boot-starter-web ์˜์กด์„ฑ์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์Šคํ”„๋ง ๋ถ€ํŠธ ํ”„๋กœ์ ํŠธ๋ฅผ ๋งŒ๋“ค๊ธฐ๋งŒ ํ•˜๋ฉด ์ฆ‰์‹œ ์›น ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ฐœ๋ฐœ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

 

@RestController
public class UserController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

์•„๋ฌด๋Ÿฐ ์„ค์ • ์—†์ด ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๋งŒ๋“ค์–ด GET /hello ์š”์ฒญ์— ๋Œ€ํ•œ ํ•ธ๋“ค๋Ÿฌ๋ฅผ ๊ตฌํ˜„ํ•˜์—ฌ ๋ฉ”์ธ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜(@SpringBootApplication)์„ ์‹คํ–‰ํ•˜๋ฉด ํ•ด๋‹น ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ์›น ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ๋™์ž‘ํ•œ๋‹ค.

 

์Šคํ”„๋ง ๋ถ€ํŠธ์˜ ๊ธฐ๋ณธ ์„ค์ •

์ด๋Š” ์Šคํ”„๋ง ๋ถ€ํŠธ๊ฐ€ ์ œ๊ณตํ•˜๋Š” ๊ธฐ๋ณธ ์„ค์ •๋•Œ๋ฌธ์— ๊ฐ€๋Šฅํ•œ ๊ฒƒ์ด๋‹ค.

META-INF/spring.factories

๊ธฐ๋ณธ ์„ค์ •์€ spring-boot-autoconfigure ๋ชจ๋“ˆ์˜ META-INF/spring.factories์— ์ •์˜๋˜์–ด ์žˆ๋‹ค.

 

 

๊ทธ ์ค‘์—์„œ๋„ ์›น MVC์— ๋Œ€ํ•œ ๊ธฐ๋ณธ ์„ค์ •์€ WebMvcAutoConfiguration์ด๋‹ค.

 

WebMvcAutoConfiguration

// Defined as a nested config to ensure WebMvcConfigurer is not read when not
	// on the classpath
	@Configuration(proxyBeanMethods = false)
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
	@Order(0)
	public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {
    ...

์ด ํด๋ž˜์Šค์˜ ๋‚ด์šฉ์„ ์‚ดํŽด๋ณด๋ฉด ๊ธฐ์กด์— ์Šคํ”„๋ง ๋ถ€ํŠธ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”, ์Šคํ”„๋ง MVC ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ฐœ๋ฐœ ์‹œ ์ง์ ‘ ์„ค์ •ํ•ด์ฃผ์–ด์•ผ ํ–ˆ๋˜ ๊ฒƒ๋“ค์ด ์Šคํ”„๋ง ๋ถ€ํŠธ์˜ ์ปจ๋ฒค์…˜์— ์˜ํ•ด ๋ฏธ๋ฆฌ ์„ค์ •๋˜์–ด ์žˆ์Œ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

 

WebMvcProperties

@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {

WebMvcProperties๋Š” application.properties์—์„œ ์‚ฌ์šฉํ•˜์—ฌ ์›น MVC์— ๋Œ€ํ•ด ์ปค์Šคํ„ฐ๋งˆ์ด์ง•ํ•  ์ˆ˜ ์žˆ๋Š” ํ”„๋กœํผํ‹ฐ๊ฐ€ ์ •์˜๋˜์–ด ์žˆ๋Š” ํด๋ž˜์Šค์ด๋‹ค.

@ConfigurationProperties์˜ prefix = "spring.mvc"๋Š” application.properties์—์„œ ์ด๋ฆ„์ด spring.mvc.*์ธ ํ”„๋กœํผํ‹ฐ์— ๋Œ€ํ•ด ๋ฐ”์ธ๋”ฉํ•œ๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค.

 

์›น MVC ๊ธฐ๋Šฅ ํ™•์žฅ

์Šคํ”„๋ง ๋ถ€ํŠธ๊ฐ€ ์ œ๊ณตํ•˜๋Š” MVC ๊ธฐ๋Šฅ์„ ๋ชจ๋‘ ์‚ฌ์šฉํ•˜๋ฉด์„œ ์ปจ๋ฒ„ํ„ฐ ์ถ”๊ฐ€, ์ธํ„ฐ์…‰ํ„ฐ ์ถ”๊ฐ€์™€ ๊ฐ™์€ ์ถ”๊ฐ€์ ์ธ ์„ค์ •์„ ํ•˜๊ณ ์ž ํ• ๋•Œ๋Š” WebMvcConfigurer๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ์„ค์ •ํŒŒ์ผ์„ ๋งŒ๋“ ๋‹ค.

 

@Configuration
public class WebConfig implements WebMvcConfigurer {

}

 

์ด ํด๋ž˜์Šค์—์„œ ์ถ”๊ฐ€ํ•˜๊ณ ์ž ํ•˜๋Š” ์„ค์ •์— ๋งž๋Š” WebMvcConfigurer์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜๋ฉด ๋œ๋‹ค.

 

References

์ธํ”„๋Ÿฐ - ๋ฐฑ๊ธฐ์„ ๋‹˜์˜ ์Šคํ”„๋ง ๋ถ€ํŠธ ๊ฐœ๋…๊ณผ ํ™œ์šฉ

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€