1. 스프링이 제공하는 컨텍스트 로더
webApplicationContext wac = contextLoader.GetCurrentWebApplicationContext (); wac.getBean (beanid);
이 방법은 서블릿에 의존하지 않으며 주입이 필요하지 않습니다. 그러나 서버가 시작되고 스프링 컨테이너가 초기화되면이 방법을 통해 스프링 컨테이너를 얻을 수 없습니다.
2. 인터페이스 ApplicationContextAware를 구현하십시오
도구 클래스를 정의합니다
공개 클래스 SpringContextUtil ApplicationContextAware {private static applicationcontext applicationcontext; // 스프링 애플리케이션 컨텍스트 환경/** * ApplicationContextAware 인터페이스의 콜백 메소드를 구현하고 컨텍스트 환경을 설정 * @Param ApplicationContext * @throws beansexception */public void setApplicationContext (ApplicationContext ApplicationContext) beansexception {SpringContextUtil.applicationContext =; } / ** * @return ApplicationContext * / public static ApplicationContext getApplicationContext () {return ApplicationContext; } / *** get object* @param name* @return 객체 주어진 이름으로 등록 된 Bean의 인스턴스* @throws beansexception* / public static object getBean (문자열 이름)은 beansexception {return applicationContext.getBean (name); } / ** * 유형의 객체를 가져옵니다. remithertype의 객체를 가져옵니다 * 콩을 유형별로 변환 할 수없는 경우 해당 예외가 발생됩니다 (BeanOtofRequiredTypeexception) * @Param Name Bean 등록 이름 * @Param Emergype Return Object 유형 * @return 객체 return return return return returntype 객체 * @throws beansection * / public retain getbean (string replite getbean) ApplicationContext.getBean (이름, 필수 유형); } / ** * beanfactory에 주어진 이름과 일치하는 Bean 정의가 포함 된 경우, return true * @param name * @return boolean * / public static boolean containbean (String name) {return applicationcontext.containsbean (name); } /*** 주어진 이름에 등록 된 Bean 정의가 싱글 톤인지 프로토 타입인지 확인하십시오. * 주어진 이름에 해당하는 Bean 정의를 찾을 수없는 경우, 예외는 (NosuchbeanDefinitionException) * @param name * @Throws NosuchBeanDefinitionException */ public static boolean issingleton (문자열 이름) throws nosuchbeandefinception (nosuchbeandefinception) {return acplication x); } / ** * @param name * @return class 등록 된 객체의 유형 * @throws nosuchbeandefinitionException * / public static class gettype (문자열 이름)는 nosuchbeandefinitionException {return applicationContext.getType (name); } / ** * 주어진 Bean 이름이 Bean 정의에 별명이있는 경우, 이러한 별칭은 * @param name * @return * @throws nosuchbeanDefinitionException * / public statiiases [] getAliases (문자열 이름) NosuchBeanDefinitionException {return ApplicationContext.getaliases (이름); }}3. 콩을 구성하십시오
<!-SpringContextutil 코드를 통해 Bean을 얻습니다 .-> <bean id = "SpringContextUtil"/>
요약
위는 스프링이 코드에서 콩을 얻는 몇 가지 방법입니다. 이 기사의 내용이 모든 사람의 연구 나 업무에 도움이되기를 바랍니다. 궁금한 점이 있으면 의사 소통을 위해 메시지를 남길 수 있습니다.