인터페이스 구현을 작성할 때 때로는 여러 구현 클래스가 있습니다. 이 기사에서는 호출 할 때 문자열을 전달하여 특정 구현 클래스를 지정하는 것을 소개합니다.
1. 인터페이스 및 구현 클래스 :
// 인터페이스 인터페이스 공개 인터페이스 ServiceInterface {public void method ();} // 두 개의 특정 구현 클래스 @service ( "aservice") public class aserviceimpl은 serviceinterface {@override public void method () {system.out.println ( "impl is a"); } @override public String toString () {return "a"; }}} @service ( "bservice") public class bserviceimpl은 serviceinterface {@override public void method () {system.out.println ( "impl is b"); } @override public String toString () {return "b"; }}ToString () 메소드는 구현 클래스에 다시 작성되며 문자열을 사용자 정의 할 수 있습니다. 호출 될 때 지정된 문자열을 전달하면 해당 콩을 얻을 수 있습니다.
2. 레지스터 쓰기 :
@Service ( "Register") public class Register 구현 초기화 비안, ApplicationContextAware {private map <string, serviceInterface> serviceimplmap = new Hashmap <> (); Private ApplicationContext ApplicationContext; // spring @override public void setApplicationContext (ApplicationContext ApplicationContext)의 컨텍스트를 가져옵니다. beansexception {this.applicationContext = applicationContext; } // 인터페이스 구현 클래스의 모든 bean을 가져 와서 설정 한 규칙에 따라 @override public void AfterProperTiesset ()이 예외 {map <string, serviceInterface> beanmap = applicationcontext.getBeansoftype (serviceInterface.class); // 다음 코드는 설정 한 규칙에 따라 Bean을지도에 넣는 것입니다. 여기에서 내 규칙은 핵심입니다. service.tostring (); 값 : Bean // 호출 할 때 서비스에 전달 된 매개 변수의 특정 문자열이 해당 Bean을 얻을 수 있습니다. // 여기에서 다음 작업을 수행 할 수 없으며 BeanMap을 직접 사용할 수 있습니다. 호출 할 때 (ServiceInterface : beanmap.values ()) {serviceimplmap.put (serviceimpl.toString (), serviceimpl)의 경우 Bean 이름이 전달됩니다 (serviceInterface) {ServiceImplMap.put (serviceImplMap.put); }} public serviceInterface getServiceimpl (문자열 이름) {return serviceimplmap.get (이름); }} 3. 테스트 클래스 :
@ResourCeregister Register; @testpublic void testservice () {serviceinterface service = register.getServiceImpl ( "a"); service.method (); ServiceInterface service2 = register.getServiceImpl ( "b"); service2.method ();}작동 결과는 그림에 나와 있습니다.
주목:
스프링로드 후 ApplyContext 방법을 가져옵니다.
ApplicationContextAware 인터페이스 Bean 구현 Bean 로딩 프로세스 중에 Spring의 ApplicationContext를 얻을 수 있습니다. 이것은 특히 중요합니다. ApplicationContext는 스프링 응용 프로그램 컨텍스트입니다. ApplicationContext에서 많은 수의 스프링 컨테이너 컨텐츠 및 모든 Bean을 포함한 정보를 얻을 수 있습니다.
@component ( "InformerRegistry") 공개 최종 클래스 정보 인 informerregistry는 ApplicationContextAware {private ApplicationContext ApplicationContext; @override public void setApplicationContext (ApplicationContext ApplicationContext)는 beansexception {this.applicationContext = ApplicationContext; }} Spring의 일반적으로 사용되는 Bean Extension 인터페이스는 http://www.cnblogs.com/xrq730/p/5721366.html을 참조하십시오.
알아채다:
Spring은 다음 방법을 사용하여 스프링 컨텍스트를 얻을 때 시작됩니다. 다음 방법을 여러 번 쓰면 여러 스프링 컨테이너가 코드를 다음과 같이 복사하기 시작합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.