> Java > java지도 시간 > 본문

Java 클래스가 Spring에서 Bean을 얻는 5가지 방법

高洛峰
풀어 주다: 2017-01-23 11:00:24
원래의
1684명이 탐색했습니다.

Spring에서 Bean을 얻는 방법은 여러 가지가 있습니다.
첫 번째 방법: 초기화 중에 ApplicationContext 객체를 저장합니다.

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");
로그인 후 복사

설명:
1. 이 두 가지 방법은 Spring 프레임워크를 통해 ApplicationContext를 얻는 데 적합합니다. ServletContext 객체를 생성하고 이를 통해 필요한 클래스 인스턴스를 얻습니다.
2. 첫 번째 메소드는 획득이 실패할 때 예외를 발생시키고 두 번째 메소드는 null을 반환합니다.
세 번째 메소드: 추상 클래스 ApplicationObjectSupport에서 상속

설명: ApplicationContext 인스턴스는 추상 클래스 ApplicationObjectSupport가 제공하는 getApplicationContext() 메소드를 통해 쉽게 얻을 수 있으며, 이후 Spring 컨테이너의 Bean은 획득. Spring이 초기화되면 추상 클래스의 setApplicationContext(ApplicationContext context) 메소드를 통해 ApplicationContext 객체가 주입된다.
네 번째 방법: 추상 클래스 WebApplicationObjectSupport에서 상속

설명: 위의 방법과 유사하게 getWebApplicationContext()를 호출하여 WebApplicationContext 인스턴스를 얻습니다.
다섯 번째 방법: ApplicationContextAware 인터페이스 구현

설명: 이 인터페이스의 setApplicationContext(ApplicationContext context) 메소드를 구현하고 ApplicationContext 객체를 저장합니다. Spring이 초기화되면 이 메소드를 통해 ApplicationContext 객체가 주입됩니다.

Spring에서는 Spring의 ApplicationContext 객체를 얻기 위해 일반 클래스에서 해당 클래스나 인터페이스를 상속하거나 구현하는 후자의 세 가지 메서드를 제공하지만, 이러한 추상 클래스나 인터페이스를 사용할 때에는 주의해야 한다. 인터페이스의 java 클래스는 Spring 구성 파일(즉, application-context.xml 파일)에서 구성되어야 합니다. 그렇지 않으면 얻은 ApplicationContext 객체는 null이 됩니다.

다음은 ApplicationContextAware 인터페이스를 구현하여 Spring 컨테이너에서 Bean을 얻는 방법을 보여줍니다.
먼저 ApplicationContextAware 인터페이스를 구현하는 클래스를 사용자 정의하고 내부에 메서드를 구현합니다.

package com.ghj.tool;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 
public class SpringConfigTool implements ApplicationContextAware {// extends ApplicationObjectSupport{
 
 private static ApplicationContext ac = null;
 private static SpringConfigTool springConfigTool = null;
 
 public synchronized static SpringConfigTool init() {
 if (springConfigTool == null) {
  springConfigTool = new SpringConfigTool();
 }
 return springConfigTool;
 }
 
 public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
 ac = applicationContext;
 }
 
 public synchronized static Object getBean(String beanName) {
 return ac.getBean(beanName);
 }
}
로그인 후 복사


다음으로 applicationContext.xml 파일에서 구성합니다.

<bean id="SpringConfigTool" class="com.ghj.tool.SpringConfigTool"/>
로그인 후 복사

마지막으로 다음 코드를 통해 Spring 컨테이너에서 해당 Bean을 가져올 수 있습니다.

SpringConfigTool.getBean("beanId");
로그인 후 복사

참고 서버가 Spring 컨테이너 초기화를 시작할 때 다음 방법으로는 Spring 컨테이너를 얻을 수 없습니다.

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
  
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
wac.getBean(beanID);
로그인 후 복사

위 내용은 이 글의 전체 내용이므로, 모두의 학습에 도움이 됩니다.

Java 클래스가 Spring에서 Bean을 얻는 5가지 방법에 대한 더 많은 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!