Spring 에서 bean 을 얻 는 방식 요약
5850 단어 ssh
그러나 시스템 에서 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 을 찾 는 것 은 쉬 운 일 입 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
SSH 키 쌍이 손실된 경우 EC2 인스턴스에 대한 SSH 연결 복원얼마 전에 안타깝게도 중요한 EC2 인스턴스에 속한 SSH 키 쌍을 잃어버렸습니다. 그 시점에서 우리는 방금 인스턴스의 스냅샷을 찍고 새 키 쌍으로 새 인스턴스를 생성했습니다. 이 블로그 게시물에서는 SSH 연결을 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.