Servlet에서 Spring Pojo Bean 을 사용할 수 있을까?
순수 자바 프로그램에서 Spring Pojo Bean 은 어떻게 사용할까?
잠깐의 구글링으로 알 수 있었다.

Spring MVC를 사용하면 Controller 를 정의하는 "xxx-servlet.xml" 을 작성하게 될 것이다.
그리고 이 Controller에서 사용하게 될 Pojo Bean 들은 "applicationContext.xml" 과 "dataAccessContext.xml" 에 정의하여 사용 할 것이다.
내가 필요한 것은 Servlet 에서 Pojo Bean 에 접근하고 싶은 것이었다.


1. Servlet 에서 Spring Pojo Bean 에 접근하는 법
  web.xml 에는 다음과 같은 태그가 정의되어 있어야 한다.

·미리보기 | 소스복사·
 
  1. <context-param>  
  2.     <param-name>contextConfigLocation</param-name>  
  3.     <param-value>/WEB-INF/dataAccessContext.xml /WEB-INF/applicationContext.xml</param-value>  
  4. </context-param>  
  5.   
  6. <listener>  
  7.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  8. </listener>  

  applicationContext.xml 에는 사용하고자하는 Pojo를 입력한다.

·미리보기 | 소스복사·
 
  1. <bean id="userPojo" class="test.UserPojo">  
  2.     <property name="userDao" ref="userDao"/>  
  3. </bean>  

당연히 userDao 는 dataAccessContext.xml 에 정의하여 두었다.

·미리보기 | 소스복사·
 
  1. <bean id="userDao" class="UserDao"></bean>  



  1.1 WebApplicationContextUtils 클래스를 사용하는 방법
    TestServlet.java 를 작성한다고 하면 userPojo 를 취해야 할 위치에 다음과 같은 코드로 객체를 취한다.

·미리보기 | 소스복사·
 
  1. WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());   
  2. UserPojo userPojo = (UserPojo)context.getBean("userPojo");  

  1.2 ServletContextAttributeExporter 클래스를 사용하여 ServletContext 에서 Attribute 로 취하는 방법
    dataAccessContext.xml 이든 applicationContext.xml 이든 어디든 상관없다. 다음과 같은 XML 태그를 설정한다.

·미리보기 | 소스복사·
 
  1. <bean class="org.springframework.web.context.support.ServletContextAttributeExporter">     
  2.   <property name="attributes">       
  3.     <map>         
  4.       <entry key="userPojo" value-ref="userPojo"/>       
  5.     </map>     
  6.   </property>  
  7. </bean>  

  이제 userPojo 를 취할 위치에서 다음과 같은 코드로 객체를 취한다.

·미리보기 | 소스복사·
 
  1. UserPojo userPojo = (UserPojo) getServletContext().getAttribute("userPojo");  

 

 


2. Pure Java Application에서 Spring Pojo Bean 에 접근하는 법
  순수 자바 프로그램은 Servlet과 같이 web.xml에 등록하는 등의 절차가 없으므로 프로그램 내에서 Spring Context를 로드하는 작업을 해주어야 한다.
  다음과 같은 프로그램으로 Spring Context를 로드할 수 있는데 프로그램이 초기화 될 때 Context 를 로드하고 프로그램 전반에서 Spring Pojo Bean 을 취하면 된다.

 

 

 

 

·미리보기 | 소스복사·
 
  1. public class UserSpringBean implements ContextSpringBean {      
  2.      
  3.     private static UserSpringBean userSpringBean = new UserSpringBean();      
  4.     private ApplicationContext ctx;

        private UserSpringBean(){      
  5.         init();      
  6.     }      
  7.     public static UserSpringBean getInstance(){      
  8.         return userSpringBean;      
  9.     }      
  10.      
  11.     private void init() {      
  12.         ctx = new ClassPathXmlApplicationContext(getContextPaths());      
  13.     }      
  14.      
  15.     public Object getBean(String beanName) {      
  16.         return ctx.getBean(beanName);      
  17.     }      
  18.      
  19.     private String[] getContextPaths() {      
  20.         String rootPath = "spring/";      
  21.         String [] paths = {      
  22.                 rootPath+"dataAccessContext.xml",      
  23.                 rootPath+"applicationContext.xml",      
  24.                 ...      
  25.         };      
  26.         return paths;      
  27.     }      
  28. }  

  그리고 프로그램 내에서는 다음과 같은 코드로 Pojo Bean 을 취한다.

 

 

 

·미리보기 | 소스복사·
 
  1. ContextSpringBean contextSpringBean = UserSpringBean.getInstance();      
  2. UserPojo userPojo = (UserPojo)contextSpringBean.getBean("userPojo");  


  물론 위의 UserSpringBean 클래스를 좀 더 편리하게 변경 가능하리라 생각한다.

 

 

 

 

 

 

 

번호 제목 글쓴이 날짜 조회 수
공지 [작성중/인프런] 스프링부트 시큐리티 & JWT 강의 황제낙엽 2023.12.20 5083
84 @ConfigurationProperties 사용하기 황제낙엽 2025.10.23 1617
83 Spring Boot 에서 서버 로직의 역할별 애노테이션 구분 황제낙엽 2025.10.13 1411
82 (확인전) [2021.03.12] Eclipse에서 Spring Boot로 JSP사용하기(Gradle) file 황제낙엽 2023.12.23 2817
81 Spring Boot PetClinic Sample Application 황제낙엽 2023.12.21 2575
80 Eclipse, Spring Boot, Gradle, SVN 레거시(2019) 시스템 유지보수 환경 구축 file 황제낙엽 2023.11.14 1732
79 [시리즈 강좌] 스프링부트로 웹서비스 구축하기 황제낙엽 2023.07.13 1691
78 Spring Boot에서의 RESTful API 모듈 file 황제낙엽 2020.04.16 1896
77 [POST] Spring MVC 구조 분석 황제낙엽 2024.01.17 2053
76 Spring Framework 에서 사용하는 annotation 황제낙엽 2024.01.17 2093
75 Spring MVC configuration file 황제낙엽 2024.01.17 2041
74 [스프링 시큐리티 OAuth2] 강의 자료와 학습용 소스 file 황제낙엽 2024.01.15 1595
73 OAuth 2.0 Resource Server - Spring Security OAuth2.0 황제낙엽 2023.12.27 2016
72 Spring, JSP, Gradle, Eclipse 환경 구축[2] - 샘플 프로젝트 file 황제낙엽 2023.12.24 1922
71 Spring, JSP, Gradle, Eclipse 환경 구축[1] - 레퍼런스 조사 황제낙엽 2023.12.23 2056
70 spring-security-samples 황제낙엽 2023.12.22 1800
69 [Bard] Spring 과 Spring Boot의 차이 file 황제낙엽 2023.12.21 1803
68 Spring 과 Spring Boot의 차이 file 황제낙엽 2020.05.26 2308
67 Spring Security OAuth2.0 파헤치기 황제낙엽 2019.09.05 2079
66 Spring Security OAuth2구현 file 황제낙엽 2019.09.05 2208
65 Spring Security OAuth 황제낙엽 2019.09.05 2442