Servlet์์ ์คํ๋ง ApplicationContext ์ฌ์ฉํ๊ธฐ
Servlet์์ ์คํ๋ง ApplicationContext ์ฌ์ฉํ๊ธฐ
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
์คํ๋ง ApplicationContext, ์ฆ ์คํ๋ง IoC๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ๊ด๋ จ ์์กด์ฑ์ ์ถ๊ฐํด์ผ ํ๋ค.
spring-context ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๊ฐ์ ธ์ฌ ์ ์๋๋ก ์์กด์ฑ์ ์ถ๊ฐํ๋ค.
์ ์์ ์์๋ spring-webmvc๋ฅผ ๊ฐ์ ธ์ค๋๋ก ํ์ง๋ง spring-context๋ง ๊ฐ์ ธ์๋ ๋๋ค.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.atoz_develop.AppConfig</param-value>
</context-param>
...
์คํ๋ง์ด ์ ๊ณตํ๋ ๋ฆฌ์ค๋์ธ ContextLoaderListener๋ฅผ ์ฌ์ฉํด์ ApplicationContext๋ฅผ ๋ง๋ค์ด ServletContext์ ์ ์ฅํ ์ ์๋ค.
๋ฐฉ๋ฒ์ web.xml์ ์์ ๊ฐ์ด ์ค์ ํ๋ ๊ฒ์ด๋ค.
<context-param>์ contextClass ํ๋ผ๋ฏธํฐ์๋ ApplicationContext์ ํ์ ์, contextConfigLocation ํ๋ผ๋ฏธํฐ์๋ ๋น ์ค์ ํ์ผ์ ์ค์ ํ๋ค.
contextClass, contextConfigLocation ํ๋ผ๋ฏธํฐ๋ช ์ ์ ์ด๋ฆ์ผ๋ก ContextLoader๊ฐ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ๋ฐ๋์ ์ง์ผ์ผ ํ๋ค.
์๋ธ๋ฆฟ
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ApplicationContext context = (ApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}
}
๋ค์์ผ๋ก ์๋ธ๋ฆฟ์์ ServletRequest๋ฅผ ํตํด ServletContext๋ฅผ ๊ฐ์ ธ์ค๊ณ , ๊ฐ์ ธ์จ ServletContext์์ attribute name 'WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE'์ ์ฌ์ฉํด์ ContextLoaderListener๋ฅผ ํตํด ๋ง๋ค์ด ์ ์ฅํ ApplicationContext๋ฅผ ๊ฐ์ ธ์ ์ฌ์ฉํ ์ ์๋ค.