sitelink1 | http://bestbang.tistory.com/8 |
---|---|
sitelink2 | http://stackoverflow.com/questions/46723...t-in-jboss |
sitelink3 | |
extra_vars6 |
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 에는 다음과 같은 태그가 정의되어 있어야 한다.
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/dataAccessContext.xml /WEB-INF/applicationContext.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
applicationContext.xml 에는 사용하고자하는 Pojo를 입력한다.
- <bean id="userPojo" class="test.UserPojo">
- <property name="userDao" ref="userDao"/>
- </bean>
당연히 userDao 는 dataAccessContext.xml 에 정의하여 두었다.
- <bean id="userDao" class="UserDao"></bean>
1.1 WebApplicationContextUtils 클래스를 사용하는 방법
TestServlet.java 를 작성한다고 하면 userPojo 를 취해야 할 위치에 다음과 같은 코드로 객체를 취한다.
- WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
- UserPojo userPojo = (UserPojo)context.getBean("userPojo");
1.2 ServletContextAttributeExporter 클래스를 사용하여 ServletContext 에서 Attribute 로 취하는 방법
dataAccessContext.xml 이든 applicationContext.xml 이든 어디든 상관없다. 다음과 같은 XML 태그를 설정한다.
- <bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
- <property name="attributes">
- <map>
- <entry key="userPojo" value-ref="userPojo"/>
- </map>
- </property>
- </bean>
이제 userPojo 를 취할 위치에서 다음과 같은 코드로 객체를 취한다.
- UserPojo userPojo = (UserPojo) getServletContext().getAttribute("userPojo");
2. Pure Java Application에서 Spring Pojo Bean 에 접근하는 법
순수 자바 프로그램은 Servlet과 같이 web.xml에 등록하는 등의 절차가 없으므로 프로그램 내에서 Spring Context를 로드하는 작업을 해주어야 한다.
다음과 같은 프로그램으로 Spring Context를 로드할 수 있는데 프로그램이 초기화 될 때 Context 를 로드하고 프로그램 전반에서 Spring Pojo Bean 을 취하면 된다.
- public class UserSpringBean implements ContextSpringBean {
- private static UserSpringBean userSpringBean = new UserSpringBean();
- private ApplicationContext ctx;
private UserSpringBean(){ - init();
- }
- public static UserSpringBean getInstance(){
- return userSpringBean;
- }
- private void init() {
- ctx = new ClassPathXmlApplicationContext(getContextPaths());
- }
- public Object getBean(String beanName) {
- return ctx.getBean(beanName);
- }
- private String[] getContextPaths() {
- String rootPath = "spring/";
- String [] paths = {
- rootPath+"dataAccessContext.xml",
- rootPath+"applicationContext.xml",
- ...
- };
- return paths;
- }
- }
그리고 프로그램 내에서는 다음과 같은 코드로 Pojo Bean 을 취한다.
- ContextSpringBean contextSpringBean = UserSpringBean.getInstance();
- UserPojo userPojo = (UserPojo)contextSpringBean.getBean("userPojo");
물론 위의 UserSpringBean 클래스를 좀 더 편리하게 변경 가능하리라 생각한다.