Spring 에서 bean 을 얻 는 방식 요약

5850 단어 ssh
Spring 프레임 워 크 는 DI 모드 를 극 대화 한 것 으로 알려 져 있 기 때문에 시스템 에서 Spring 이 관리 하 는 Bean 으로 서로 가 져 오 는 것 이 매우 편리 합 니 다. 사용자 가 setter 방법 을 제공 하고 설정 파일 에 이 속성 을 설정 하면 됩 니 다.
그러나 시스템 에서 Spring 프레임 워 크 관리 가 아 닌 클래스 에 대해 Spring 관리 클래스 를 가 져 오 거나 프로그램 에서 Bean 의 id 에 따라 동적 으로 Bean 인 스 턴 스 를 가 져 와 야 한다 면 필요 한 Bean 속성 을 모두 제공 하 는 setter 방법 을 미리 제공 할 수 없다. 이와 같은 상황 에서 Spring 프레임 워 크 관리 클래스 의 인 스 턴 스 를 가 져 오 는 방법 은 여러 가지 가 있다.지금 간단하게 요약 하면 다음 과 같다.
 
방법 1: 애플 리 케 이 션 Context 대상 을 초기 화 할 때 저장 합 니 다.
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");

  ac.getBean("beanId");
             Spring         ,               Spring   。
   :  Spring        ApplicationContext  
import org.springframework.web.context.support.WebApplicationContextUtils;


ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc)
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);ac1.getBean("beanId");
ac2.getBean("beanId");

이러한 방식 은 Spring 프레임 워 크 를 사용 하 는 B / S 시스템 에 적합 하 며, ServletContext 대상 을 통 해 applicationContext 대상 을 가 져 온 다음 필요 한 인 스 턴 스 를 가 져 옵 니 다.
           ,         ServletContext       。   getWebApplicationContext()     WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE                   null。  ,           NullPointerExceptions ,        getRequiredWebApplicationContext()   。     ApplicationContext             。
            ,            ,    null。
     :      ApplicationObjectSupport
   ApplicationObjectSupport  getApplicationContext()ApplicationContext。Spring    ,        setApplicationContext(ApplicationContext context)   ApplicationContext     。

방법 4: 추상 적 인 웹 애플 리 케 이 션 Object Support 계승 위의 방법 과 같이 getWebapplicationContext () 를 호출 하여 WebapplicationContext 를 가 져 옵 니 다. 
방법 5: 인터페이스 응용 프로그램 ContextAware 실현 이 인터페이스의
setApplicationContext( ApplicationContext context) 방법, 응용 프로그램 Context 저장 대상Spring 을 초기 화 할 때 이 방법 을 통 해 Application Context 를 대상 주입.
저 는 웹. xml 에서 설정 한 다음 에 하나의 모니터 로 클래스 를 호출 하여 직접 읽 습 니 다. tomcat 가 시 작 될 때 실 행 됩 니 다.
web.xml
 contextConfigLocation
 /WEB-INF/config/spring/applicationContext.xml
 
  com.wzw.listener.SpringListener
 
SpringListener package com.wzw.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.wzw.spring.common.SpringBeanFactory;
public class SpringListener implements ServletContextListener {
 public void contextInitialized(ServletContextEvent sce) {
  // TODO Auto-generated method stub
String relativePath = sce.getServletContext().getInitParameter(
"contextConfigLocation");
String realPath = sce.getServletContext().getRealPath(relativePath);
SpringBeanFactory.init(realPath);
 }

 public void contextDestroyed(ServletContextEvent arg0) {   // TODO Auto-generated method stub  SpringBeanFactory.clear(); }
}
모니터 가 호출 하 는 클래스 패키지 com. wzw. spring. comon;import java.util.Locale; import org.apache.struts.action.ActionMessage; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.context.ApplicationContext;public class SpringBeanFactory {     private static ApplicationContext context;    /**     * 프로그램 시작 시 spring 프레임 워 크 설정    *     * @param filePath     */    public static void init(String filePath) {     if (context == null) {        context = new FileSystemXmlApplicationContext(filePath);     }   }    public static ApplicationContext getContext(){     return context;    }    /**     * 방법 은 업무 대상 을 얻 는 데 쓰 인 다.    *     * @param beanName     * @return     */    public static Object getBusinessOjbect(String beanName) {     return context.getBean(beanName);    }    /**     * 프로그램 이 닫 혔 을 때 spring 프레임 워 크 설정 정 보 를 비 웁 니 다.    */    public static void clear() {     if (context != null) {      context = null;     }    } } 이렇게 하면 응용 프로그램 을 찾 을 수 있 습 니 다. 설정 이 정확 하면 응용 프로그램 을 통 해 bean 을 찾 는 것 은 쉬 운 일 입 니 다!

좋은 웹페이지 즐겨찾기