머리말
Javaconfig는 봄의 하위 프로젝트로 판명되었습니다. Java 클래스를 통해 Bean 정의 정보를 제공합니다. Spring4 버전에서 Javaconfig는 공식적으로 Spring4의 핵심 기능이되었습니다.
이 기사는 봄의 Java 클래스를 기반으로 한 구성에 대한 관련 컨텐츠를 자세히 소개합니다. 나는 아래에서 많이 말하지 않을 것입니다. 자세한 소개를 함께 살펴 보겠습니다.
1 정의 Bean
평범한 pojo는 @Configuration 주석이 표시되는 한 스프링 컨테이너에 대한 Bean 정의 정보를 제공 할 수 있습니다.
@ConfigurationPublic Class SystemConfig { / ** * Bean 및 Instantiate * * @return * / @bean public userdao userdao () {return new userDao (); } @bean public deptdao deptdao () {return new deptdao (); } / ** * uservice를 정의하고 이전에 정의 된 userdao 및 deptdao * * @bean public userervice userervice () {uservice service = new UserserVice (); service.setuserdao (userDao ()); service.setdeptdao (deptdao ()); 반품 서비스; }}이 클래스의 방법은 @bean 주석, 즉 콩을 정의하기 위해 주석을 달 수 있습니다. 콩의 유형은 메소드 리턴 값의 유형에 따라 결정됩니다. 이름은 메소드 이름과 메소드 이름으로 기본적으로 기본적으로 표시됩니다. @Bean (name =”xxx”)과 같은 매개 변수를 입력하여 Bean 이름을 지정할 수도 있습니다. @Bean으로 표시된 본문은 콩을 인스턴스화하는 논리를 제공합니다.
위 구성은 다음 XML과 같습니다.
<bean id = "userdao"/> <bean id = "deptdao"/> <bean id = "uservice"p : userdao-ref = "userdao"p : deptdao-ref = "deptdao"/>
XML 또는 주석 기반 구성 방법을 기반으로하는 Java 클래스를 기반으로 한 구성 방법과 비교하여 -
@Configuration 주석 클래스 자체에는 @Component가 있으므로 이러한 클래스는 일반 콩과 같은 다른 콩에 주입 할 수 있습니다.
@ConfigurationPublic 클래스 ApplicationConfig {@autowired private SystemConfig SystemConfig; @Bean Public AuthorityService AuthorityService () {AuthorityService Service = New AuthorityService (); service.setuserdao (SystemConfig.userDao ()); service.setdeptdao (SystemConfig.deptdao ()); 반품 서비스; }}Spring은 구성 클래스에서 @Bean으로 표시된 모든 방법에 대해 AOP 향상을 사용하여 Bean의 수명주기 관리 논리를 소개합니다. 예를 들어, 위의 SystemConfig.userdao ()는 Bean에 해당하는 싱글 톤을 반환합니다.
@Bean에서는 @Scope 주석에 주석을 달아 Bean의 범위를 제어 할 수 있습니다.
@scope ( "프로토 타입")@beanpublic deptdao deptdao () {return new deptdao ();}이런 식으로, deptdao () 메소드에 대한 각 호출은 새 인스턴스를 반환합니다.
AssertNotsame (AuthorityService.getDeptDao (). hashcode (), AuthorityService.getDeptdao (). hashcode ());
참고 : 구성에는 Java 기반 클래스를 사용하여 Spring AOP 및 CGLIB 라이브러리가 클래스 경로에 포함되어야합니다.
2 스프링 컨테이너를 시작하십시오
2.1 @configuration 클래스 만 사용하십시오
AnnotationConfigApplicationContext 클래스의 생성자를 사용하여 @Configuration으로 표시된 Java 클래스에서 스프링 컨테이너를 시작할 수 있습니다.
ApplicationContext Context = New AnnotationConfigApplicationContext (SystemConfig.class); userErvice userErvice = (userErvice) context.getBean ( "userErvice"); AsserTNOTNULL (usersERVICE);
여러 @Configuration 구성 클래스가있는 경우 AnnotationConfigApplicationContext에 등록한 다음 컨테이너를 새로 고쳐서 이러한 구성 클래스를 적용 할 수 있습니다.
AnnotationConfigApplicationContext Context = New AnnotationConfigApplicationContext (); // 여러 구성 클래스 Context.register (SystemConfig.class); Context.Register (ApplicationConfig.class); // 컨테이너 새로 고침 (ApplicationConfig); refresh (); config = context.getBean (ApplicationConfig.class); assertNotNull (config);
@Import를 통해 여러 구성 클래스를 하나의 구성 클래스로 조립 한 다음 조립 된 구성 클래스를 등록하여 컨테이너를 시작할 수 있습니다.
@configuration @import (SystemConfig.class) 공개 클래스 ApplicationConfig2 {@autowired private systemconfig systemconfig; @Bean Public AuthorityService AuthorityService () {AuthorityService Service = New AuthorityService (); service.setuserdao (SystemConfig.userDao ()); service.setdeptdao (SystemConfig.deptdao ()); 반품 서비스; }}단위 테스트 :
AnnotationConfigApplicationContext Context = New AnnotationConfigApplicationContext (ApplicationConfig2.class); ApplicationConfig2 config = context.getBean (ApplicationConfig2.class); AsserTNOTNULL (config); 최종 권한 서비스 권한 장관이 = config.authorityService (); assertNotnull (AsserviceService.getDeptdao ()); assertNotsame (AsserverService.getDeptDao (). hashcode (), 권위 .getDeptdao (). hashcode ());
2.2 XML 파일을 사용하여 @Configuration 클래스의 구성을 참조하십시오.
@Configuration으로 표시된 구성 클래스는 또한 Bean이므로 Spring의 <Context : Component-Scan>으로도 스캔 할 수도 있습니다. 따라서 구성 클래스를 XML 구성 파일로 조립하고 XML 구성 파일을 통해 Spring을 시작하려면 XML의 <Context : Component-Scan>을 통해 해당 구성 클래스를 스캔하면됩니다.
<context : component-scan base-package = "net.deniro.spring4.conf"resource-pattern = "applicationconfig2.class" />
2.3 @Configuration 클래스의 참조 XML 파일 구성
@Configuration Configuration 클래스에서 @importresource를 통해 XML 구성 파일을 직접 소개하여 @autowired를 통해 XML 구성 파일에 정의 된 Bean을 직접 참조 할 수 있습니다.
구성 파일 :
<bean id = "groupdao"/> <bean id = "roledao"/>
@Configuration 클래스 :
@Importresource ( "classpath : beans5-11.xml") @configurationPublic Class ServiceConfig {@bean @autowired public relationservice relationservice (GroupDao GroupDao, Roledao Roledao) {relationService service = new chelationservice (); service.setgroupdao (GroupDao); Service.setRoledao (Roledao); 반품 서비스; }}단위 테스트 :
AnnotationConfigApplicationContext Context = New AnnotationConfigApplicationContext (serviceConfig.class); serviceConfig config = context.getBean (serviceConfig.class); assertNotnull (config); relationservice service = config.relationservice (groupdao) ( "GroupDao", Getgedao ") (ROLEDAO) CONTEXT .GETBEAN ( "ROLEDAO")); ASSERTNOTNULL (service.getRoleDao ());
이러한 형태의 콩에 대한 이러한 정의 정보가 스프링 컨테이너에로드 될 수있는 한, Spring은 콩 사이의 조립을 지능적으로 완성 할 수 있습니다.
요약
위는이 기사의 전체 내용입니다. 이 기사의 내용에 모든 사람의 연구 나 작업에 대한 특정 참조 가치가 있기를 바랍니다. 궁금한 점이 있으면 의사 소통을 위해 메시지를 남길 수 있습니다. Wulin.com을 지원 해주셔서 감사합니다.