1. 참고
주석은 주석과 유사한 메커니즘입니다. 코드에 주석을 추가하면 나중에이 정보를 사용할 수 있습니다. 의견과 달리 의견은 우리가 볼 수 있습니다. Java 가상 머신은 컴파일 할 수 없으며 주석이 컴파일되지 않지만 반사 메커니즘을 통해 주석의 정보를 읽을 수 있습니다. 주석은 키워드 @interface를 사용하여 java.lang.annotition.annotation을 상속합니다
1. Javase의 주석
Javase의 주석이 무엇인지 검토 할 수있는 예를 들어 드리겠습니다. 키는 주석의 정의와 반사를 통해 주석 위의 정보를 얻는 방법의 두 가지 요점입니다.
1. 먼저 두 개의 주석을 정의합니다. 하나는 클래스에서 주석이 달린 classInfo이고 다른 하나는 메소드에서 주석이 달린 MethodInfo입니다.
classinfo
package com.itheima10.annotation; import java.lang.annotation.documented; import java.lang.annotation.elementtype; import java.lang.annotation.retention; import java.lang.annotation.retentionpolicy; import java.lang.annotation.targge (elecompepe.lang.annotation.targge). 클래스 @retention (rendentionpolicy.runtime)에서 사용되면 // Java에서 클래스 파일 및 런타임 주석 @documented // 문서에서 생성 될 수 있습니다 @interface classInfo { /** *이 주석에는 문자열 유형의 두 가지 속성이 있습니다. 문자열 값 () 기본값 "";}MethodInfo
패키지 com.itheima10.annotation; import java.lang.annotation.documented; import java.lang.annotation.elementtype; import java.lang.annotation.retention; import java.lang.annotation.retentionpolicy; import java.lang.annotation.targge (elecompepe.montod) //targge. 메소드 @retention (rendentionpolicy.runtime) // java에서, 클래스 파일 및 런타임 주석 @documented // help document public @interface methodinfo { /*** 문자열 유형* /string name () default "의 두 가지 속성이 있습니다. 문자열 값 () 기본값 "";}2. 위에서 정의 된 주석을 사용하려면 주석 클래스를 작성하십시오.
package com.ithema10.annotation; @classinfo (name = "xiaopingguo118", value = "niu") public class annotationuse {@methodinfo (name = "java", value = "spring framework is moratial") public void java () {}}3. 테스트 클래스 주석 테스트를 작성하고 두 주석 위의 속성을 구문 분석하십시오.
package com.ithema10.annotation; import java.lang.reflect.method; import org.junit.test; public class annotationTest {public static void test () { / ** * 클래스의 주석을 구문 분석하는 경우, 메소드의 주석을 구문 분석하면 먼저 클래스를 얻으려면 * / class class1 = ItHeima10.class; // 클래스에 classInfo 주석이 있는지 판단 if if (class1.isannotationPresent (classInfo.class)) {// classClassInfo classInfo = (classInfo) class1.getAnnotation (classInfo.class)에서 주석을 가져옵니다. System.out.println (classInfo.Value ()); System.out.println (classinfo.name ()); } method [] method = class1.getMethods (); for (method method : methods) {// if (method.isannotationPresent (methodInfo.class)) {methodInfo methodInfo = method.getAntation (methodInfo.class); System.out.println (MethodInfo.name ()); System.out.println (MethodInfo.Value ()); }}} @test public void test () {annotationTest.test (); }}2. 봄의 주석
스프링 프레임 워크는 우리에게 주석 기능을 제공합니다.
주석 프로그래밍을 사용하는 것은 주로 XML 파일을 대체하고 개발을 더 빨리 만들기위한 것입니다. 그러나 XML 파일의 사용은 프로그램의 소스 코드를 수정하는 문제를 해결하는 것입니다. 이제 XML 파일을 사용하지 않으므로 개방 및 폐쇄 원리를 위반하지 않습니까? 사실입니다. 그러나 주석도 양호하므로 주석을 사용할 때 많은 XML 파일을 구성 할 필요가 없습니다. 가장 중요한 것은 개발 효율성이 높다는 것입니다. .
주석이 사용되지 않으면 스프링 프레임 워크의 구성 파일 ApplicationContext.xml 파일에서 많은 <ean> 태그를 구성해야합니다. 주석을 사용하여 구성 파일에 태그 풀을 추가 할 필요가 없으며 해당 설명은 해당 클래스의 "주석"위치에 지침을 추가하는 것입니다. 특정 소개는 다음과 같습니다.
• 1. @Resource 객체 간의 관계의 조합은 기본값이 이름으로 조립하는 것입니다. 이름에 따라 관련 객체를 찾을 수 없으면 유형별 검색이 계속됩니다. 이름 속성이 지정되지 않은 경우
• 주석이 필드에 표시되면 기본값은 필드 이름을 Bean 이름으로 가져 가서 종속성 개체를 찾는 것입니다.
• 주석이 속성의 Setter 메소드에 표시되면 기본 속성 이름은 종속성 객체를 찾기 위해 Bean 이름으로 사용됩니다.
• 참고 : 이름 속성이 지정되지 않고 기본적으로 종속성 객체를 찾을 수없는 경우 @Resource 주석은 유형별로 어셈블리로 떨어집니다. 그러나 이름 속성이 지정되면 이름으로 만 조립할 수 있습니다.
• 2. @autowired
@autowired는 기본적으로 유형별로 조립되며 @Resource는 기본적으로 이름별로 조립되며 이름과 일치하는 Bean을 찾을 수없는 경우에만 유형별로 조립됩니다. 해결책은 종속 객체를 유형별로 조립하는 것입니다. 기본적으로 종속 객체가 존재해야합니다. NULL 값이 허용되면 False로 설정할 수 있습니다.
• 3. @Qualifier
이름으로 어셈블리를 사용하려면 @Qualifier 주석과 함께 사용할 수 있습니다.
1. 주석을 사용하려면 구성 파일에 네임 스페이스 및 구속 파일 단계를 추가해야합니다.
컨텍스트 네임 스페이스 소개
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"
xmlns : context = "http://www.springframework.org/schema/context"
...
http://www.springframework.org/schema/context/spring-context-2.5.xsd ">
2. 컨텍스트 추가 : 구성 파일에 주석 -Config 태그를 추가하십시오
<컨텍스트 : 주석 -Config> </context : Annotation-Config>
예제 시연 :
학생 속성과 say () 메소드가있는 사람 클래스를 작성하십시오. 코드는 다음과 같습니다
package com.itheima10.spring.di.annotation; import javax.annotation.resource; import org.springframework.bean.beans.annotation.autowired; import org.springframework.beans.com.annotation.qualifier;/** @autowired* @autowired/ @autowired* @autowired/matching* @autowired/matche* @autowired/matching* @autowired/matche* @autowired/matche* @ * */public class person {@resource (name = "학생") 사립 학생 학생; public void says () {this.student.say (); }}학생 수업 코드는 다음과 같습니다
package com.ithema10.spring.di.annotation; public class 학생 {public void say () {System.out.println ( "학생"); }}ApplicationContext.xml 파일을 구성하십시오
<? xml version = "1.0"encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : context = "http://www.springframework.org/schema/context" xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xsi : schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/schema/schema/schema/schema/schemys-2 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "> <!-봄 컨테이너-> <bean id ="person "> <bean id ="</bean "> xmlns : context = "http://www.springframework.org/schema/context"http://www.springframework.org/schema/context http://www.springframework.org/schema/context/sprring-contex-5 시작된 이후로 주입 된 파서-> <context : Annotation-Config> </context : Annotation-Config> </beans>
테스트 클래스 주석 테스트를 작성하십시오
package com.itheima10.spring.di.annotation; import org.junit.test; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext;/** arepiner :* 2 시작* 2. the bean and inst the beans and inst inst inst the bean and inst inst the spring and instan 스프링 컨테이너는* <context : Annotation-Config> </context : annotation-config>*, 의존성 주입을위한 주석 파서가 시작됩니다* 4. 4. 스프링 컨테이너는 스프링 관리에 포함 된 Bean의 범위 내에서 @resource에 추가 될지 여부*, @resource가 추가 될지 여부를 확인하기 위해 스프링 관리에 포함 된 Bean의 범위 내에서 찾아 볼 것입니다. 주석의 이름 속성의 값은 "" * 인 경우 "" ""주석이 위치한 속성의 이름과 스프링 컨테이너의 ID 값과 일치합니다. 경기가 성공하면 과제 * 경기가 실패하면 유형에 따라 할당이 수행됩니다. 경기가 성공하면 과제가 할당됩니다 * 경기가 실패하면 과제가보고됩니다. * 경기가 실패하면 경기가 직접보고됩니다 * 경기가 성공하지 못하면 과제가보고되면, 할당이 성공하지 못하면, 할당이 성공하지 못하면, 할당이보고되지 않을 것입니다. 참조 유형 XML 및 주석. 효율은 비교적 높습니다. 글쓰기는 더 번거 롭습니다. 주석 작성은 비교적 간단하고 덜 효율적입니다 * */public class annotationTest {@test public void testAnnotation () {ApplicationContext context = new ClassPathXmlApplicationContext ( "ApplicationContext.xml"); 개인 = (사람) context.getBean ( "사람"); person.say (); }}주석을 사용하는 경우 구성 파일에 사람과 학생을로드 할 필요가 없으므로 구성 파일 작성을 단순화 할 수 있습니다.
3. 스캔
이전 예제에서는 XML Bean 정의를 사용하여 구성 요소를 구성했습니다. 약간 더 큰 프로젝트에는 일반적으로 수백 개의 구성 요소가 있습니다. 이러한 구성 요소가 XML Bean 정의를 사용하여 구성되면 구성 파일의 크기가 높아져 찾고 유지 관리가 매우 편리하지 않습니다. Spring2.5는 우리를위한 자동 구성 요소 스캔 메커니즘을 소개합니다.이 클래스는 클래스 경로 아래에 @component, @service, @controller 및 @repository 주석으로 주석이 달린 클래스를 찾을 수 있으며 이러한 클래스를 스프링 컨테이너에 통합하여 관리 할 수 있습니다. 함수는 XML 파일에서 Bean Node 구성 구성 요소를 사용하는 것과 동일합니다. 자동 스캔 메커니즘을 사용하려면 다음 구성 정보를 열어야합니다.
1. 컨텍스트 네임 스페이스를 소개합니다
컨텍스트 추가 : XML 구성 파일의 구성 요소 스캔 태그
여기서 기본 패키지는 스캔 해야하는 패키지 (서브 포장)입니다.
예:
위의 예는 다음과 같이 스캔 모드로 작성됩니다.
@ComponentPublic Class Person {@Resource (name = "Student") 사립 학생 학생; public void says () {this.student.say (); }}@ComponentPublic 클래스 학생 {public void say () {system.out.println ( "학생"); }}ApplicationContext.xml은 한 문장으로 만 구성하면됩니다
<!-구성 요소 구성 요소는 클래스를 스프링 컨테이너에 넣고 클래스는 패키지 아래에 구성 요소를 스캔하고 기본 패키지로 지정된 서브 포장이라고합니다-> <context : component-scan base-package = "com.itheima10.spring.scan"> </context : component-scan>
테스트 클래스 주석 테스트를 작성하십시오
/*** 원리* 1. 스프링 컨테이너 시작* 2. 스프링 컨테이너 구문 분석* <context : component-scan base-package = "com.iSheima10.spring.scan"> </context : component-scan> 3. 기본 팩케에 의해 지정된 패키지 및 하위 포장지가 어떤 클래스를 포함하는지 @component annotation @annot @component @component @component @component @component @component가 포함됩니다. == <bean id = "person"> @component ( "aa") 공개 클래스 사람 {} == <bean id = "aa"> 5에 해당합니다. @Resource의 분석 단계를 따르십시오 : 전체 프로세스가 두 번 스캔되고, 효율성이 더 낮아지고 더 쉬워지고 있으며, 글쓰기가 더 쉽고 더 쉬워지고 있으며, * */public class test {@Toid textont () {@Toid textont () {public class antalt (). new ClassPathXmlApplicationContext ( "ApplicationContext.xml"); 개인 = (사람) context.getBean ( "사람"); person.say (); }}인스턴스의 다시 나타납니다
주석에서 Item51의 마지막 문서 관리 시스템을 변경합니다. 문서 인터페이스는 읽기 및 쓰기 방법으로 변경되지 않았습니다. 구현 클래스는 ExcelDocument, PDFDocument 및 WordDocument와 같습니다.
@Component ( "ExcelDocument") 공개 클래스 ExcelDocument emplements 문서 {public void read () {System.out.println ( "Excel read"); } public void write () {System.out.println ( "Excel Write"); }}@component ( "pdfdocument") public class pdfdocument emplements 문서 {public void read () {system.out.println ( "pdf read"); } public void write () {system.out.println ( "pdf write"); }}@component ( "wordDocument") public class wordDocument emplics {public void read () {system.out.println ( "Word read"); } public void write () {System.out.println ( "Word Write"); }}DocumentManager
@Component ( "DocumentManager") 공개 클래스 DocumentManager {@Resource (name = "ExcelDocument") 개인 문서 문서; public void read () {this.document.read (); } public void write () {this.document.write (); }}구성 파일
<context : component-scan base-package = "com.iSheima10.spring.iocdi.document">
</context : component-scan>
테스트 클래스 문서 테스트를 작성하십시오
public class documentTest {@test public void testDocument () {ApplicationContext context = new ClassPathXmlApplicationContext ( "ApplicationContext.xml"); DocumentManager DocumentManager = (DocumentManager) Context.GetBean ( "DocumentManager"); DocumentManager.Read (); DocumentManager.write (); }} 2. 다른 주석 기능 소개
@Service는 비즈니스 계층 구성 요소 및 서비스 계층 주석에 주석을 달 때 사용됩니다.
@Controller는 제어 레이어 구성 요소 (예 : 스트럿의 동작) 및 제어 레이어 주석에 주석을 달아 사용하는 데 사용됩니다.
@repository는 데이터 액세스 구성 요소, 즉 DAO 구성 요소에 주석을 달 때 사용됩니다. 지속성 층 주석
@Component는 구성 요소를 나타냅니다. 구성 요소를 분류하기 쉽지 않은 경우이 주석을 사용하여 주석을 달 수 있습니다.
예제는 MVC 사례를 재현합니다
우리는 Item51의 MVC 사례를 다시 검토하여 Persondaoimpl, Personaction 및 PersonserviceImpl의 DAO, 서비스 및 액션 레이어를 각각 추가하여 Persondaoimpl의 DAO, 서비스 및 액션 레이어에 각각 주석을 추가합니다.
@repository ( "persondao") 공개 클래스 persondaoimpl은 persondao {@override public void saveperson () {system.out.println ( "Save Person"); }} @service ( "personservice") 공개 클래스 personserviceimpl은 personservice {@resource (name = "persondao") private persondao persondao; 공개 void setpersondao (persondao persondao) {this.persondao = persondao; } @override public void saveperson () {this.persondao.saveperson (); }} @Controller ( "PersonAction") 공개 클래스 인원 {@Resource (name = "personservice") private personservice personservice; public void setpersonservice (personservice personservice) {this.personservice = personservice; } public void saveperson () {this.personservice.saveperson (); }}테스트 mvctest를 작성하십시오
공개 클래스 mvctest {@test public void testmvc () {ApplicationContext context = new ClassPathXmlApplicationContext ( "ApplicationContext.xml"); 인물 적 성격 = (Personaction) context.getBean ( "Personaction"); personaction.saveperson (); }}4. 봄의 상속
스프링은 상속을지지하며, 이는 클래스 상속 및 속성 상속으로 나눌 수 있습니다.
1. 클래스 상속
스프링 속성 :
(1) 요약 : 진실로 설정되면 정의 된 콩이 추상적이라는 것을 의미합니다. Spring에게 콩을 인스턴스화하지 말라고 말하십시오.
질문 : 추상 수업이어야합니까? 추상 수업 일 수 있습니까?
(2) 부모 : Bean의 콩 ID 기능을 나타내며, 이는 Java 클래스에서 확장 기능과 동일합니다.
장면 : 3 개의 콩이 있습니다.
<bean id = "bean1"class = "… testbean"> <속성 이름 = "sex"value = "male"/> </bean> <bean id = "bean2"class = "… testbean"> <property name = "sex"value = "male"/> </bean> <bean id = "bean3"class = "… testbean"> value = "value ="femal ""/bean ".
수정 : 스프링 부모 Bean을 정의하십시오
<bean id = "basebean"class = "… testbean"> <property name = "sex"value = "male"/> </bean>
하위 빈을 정의하십시오
<bean id = "bean1"parent = "basebean"/> 부모 bean <bean id = "bean2"parent = "basebean"/> <bean id = "bean3"parent = "basebean"> 상위 bean <property name = "sex"value = "female"/> </bean>의 속성을 상속받습니다.
어린이 콩은 부모 콩의 특성을 물려 받거나 부모 콩의 특성을 무시할 수 있습니다.
2. 속성 상속
여러 다른 콩 사이에는 동일한 속성이 있으며 장면을 추출 할 수 있습니다.
<bean id = "bean1"class = "… atestbean"> <property name = "sex"value = "male"/> <property name = "task"ref = "task"/> </bean> <bean id = "bean2"class = "… btestbean"> <속성 이름 = "sex"value = "male"/> </bean
수정 : (1) 공개 속성 추출
<bean id = "BaseSex"acpract = "true"> <속성 이름 = "sex"value = "male"/> </bean>
(2) 콩 수정
<bean id = "bean1"class = "… atestbean"parent = "baseesx"> <property name = "task"ref = "task"/> </bean> <bean id = "bean2"class = "… btestbean"parent = "Basesex"/>
여기서 콩은 부모와 클래스 속성을 모두 가지고 있으며, 부모가 지적한 Basesex는 다른 콩이 동일한 속성 값을 공유하도록 허용하는 것입니다. TransactionProxyFactoryBean이 서비스를 선언 할 때 Bean 속성의 상속은 중복 XML 구성을 크게 줄일 수 있습니다.
주석 기반 상속은 부모 속성이 필요하지 않습니다.
작은 요약 사진을 마지막으로하자
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.