Spring(2):Spring 은 IOC 를 통 해 대상 을 만 듭 니 다.

16346 단어 SpringIOC대상
1.IOC 는 대상 을 어떻게 얻 습 니까?
1.1 Spring 은 어떻게 대상 을 얻 습 니까?
① Maven 프로젝트 를 새로 만 든 후 웹 뮤 직 비디오 c 를 가 져 오 는 의존:웹 뮤 직 비디오 c 는 다른 의존 도 를 많이 포함 하고 있 기 때문에 편리 하 게 가 져 옵 니 다!버 전 이 잖 아!개인 적 으로 최신 판 을 즐겨 씁 니 다.

    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.5</version>
    </dependency>

② 새 실체 테스트 클래스:

public class Person {
    private String name;
    private int age;
    private String like;
    private String high;
    //get、set、tostring        ,         lombok
}
③ resources 디 렉 터 리 에 ContextAplication.xml 파일 을 새로 만 듭 니 다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="Person" class="entity.Person">
        <property name="age" value="23"></property>
        <property name="name" value="   "></property>
        <property name="like" value="  "></property>
        <property name="high" value="173"></property>
    </bean>
</beans>
④ 이상 의 전 제 를 거 친 후에 테스트 Person 종류 에 변화 가 생 겼 음 을 발견 할 수 있 습 니 다.클릭 하면 지정 한 xml 위치 로 이동 할 수 있 습 니 다~
在这里插入图片描述
⑤ 테스트:
Context.getBean()이 클래스 를 지정 하지 않 을 때 강제 변환 이 필요 하기 때문에 두 번 째 방식 으로 대상 을 가 져 오 는 것 을 권장 합 니 다.

public class Test {
    public static void main(String[] args) {
        ApplicationContext Context = new ClassPathXmlApplicationContext("ContextAplication.xml");
//        Person person = (Person) Context.getBean("Person");//           ,            
        Person person = Context.getBean("Person",Person.class);
        System.out.println(person);
    }
}

⑥ 실행 결 과 는 다음 과 같 습 니 다:성공 적 으로 값 을 받 았 습 니 다!
在这里插入图片描述
⑦ 총괄:
  • 제어:전통 적 인 프로그램 대상 의 생 성 은 프로그램 이 제어 하여 만 든 것 입 니 다.
  • 반전:Spring 용기 에 맡 겨 대상 을 만 들 고 프로그램 은 수 동적 인 수신 대상 만 책임 집 니 다.이게 반전 이 야.
  • 의존 주입:set 방법 으로 주입 한 것 이다.
  • 1.2 개조 사례 는 xml 에서 생 성 대상 을 선택 합 니 다.
    ①xml:
    
     <bean id="StudentMapperImpl" class="mapper.impl.StudentMapperImpl"/>
        <bean id="TeacherMapperImpl" class="mapper.impl.TeacherMapperImpl"/>
        <bean id="PersonServiceImpl" class="service.impl.PersonServiceImpl">
            <property name="studentMapper" ref="StudentMapperImpl"/>
        </bean>
    
    ② 테스트:
    
            ApplicationContext Context1 = new ClassPathXmlApplicationContext("ContextAplication.xml");
            PersonServiceImpl personServiceImpl = Context1.getBean("PersonServiceImpl", PersonServiceImpl.class);
            personServiceImpl.getPersonInfo();
    
    ③ 실행 결과:
    在这里插入图片描述
    ⑤ 요약:
    대상 은 Spring 에서 만 들 고 관리 하 며 조립 합 니 다!이게 IOC 야!
    2.IOC 는 어떤 방식 으로 대상 을 만 듭 니까?
    2.1 무 참 구조 함수 로 대상 만 들 기
    ① Person 류 를 예 로 들 지만 무 참 구조 함 수 를 추가 합 니 다!
    
    public class Person {
        private String name;
        private int age;
        private String like;
        private String high;
        public Person() {
            //             !
            System.out.println("  Person        !     !!!!");
        }
        //set、get、tostring          ,     !
    }
    
    ② xml 설정:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="Person" class="entity.Person">
            <property name="age" value="23"></property>
            <property name="name" value="   "></property>
            <property name="like" value="  "></property>
            <property name="high" value="173"></property>
        </bean>
    </beans>
    
    
    ③ 테스트 클래스:
    
    public class Test {
        public static void main(String[] args) {
            ApplicationContext Context = new ClassPathXmlApplicationContext("ContextAplication.xml");
            Person person = Context.getBean("Person", Person.class);
            System.out.println(person);
        }
    }
    
    
    ④ 집행 결과:
    在这里插入图片描述
    ⑤ 무 삼 구 조 를 제거 하고 유 삼 구 조 를 늘린다.
    在这里插入图片描述
    xml 설정 프로그램 오류 직접 보고:
    在这里插入图片描述
    ⑥ 결론:
    Spring 생 성 대상 은 기본적으로 무 참 구조 함수 로 만 들 어 졌 습 니 다!구조 함수 가 있어 서 대상 을 만 들 수 있 습 니까?네!아래 봐!
    2.2 참조 구조 방법 으로 대상 만 들 기
    ① 전 제 는 2.1 이 일치 하 는 것 을 전제 로 삼 구조 함수 가 새로 추 가 됩 니 다.(클래스 에서 기본 적 인 것 은 구조 적 인 파 라 메 터 를 쓰 지 않 으 면 무 삼 구조 이 고 삼 구조 가 있어 야 진정한 의미 에서 무 삼 구 조 를 제거 할 수 있 기 때 문 입 니 다.이 건 너무 많이 설명 하지 않 아 도 됩 니 다.자바 기반 의 내용 입 니 다~!)
    
        public Person(String name, int age, String like, String high) {
            this.name = name;
            this.age = age;
            this.like = like;
            this.high = high;
        }
    
    
    ② xml 설정 파일 에 변경 사항 이 있어 야 합 니 다.
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="Person" class="entity.Person">
    <!--        <property name="name" value="   "></property>-->
    <!--        <property name="age" value="23"></property>-->
    <!--        <property name="like" value="  "></property>-->
    <!--        <property name="high" value="173"></property>-->
            <constructor-arg index="0" value="   "/>
            <constructor-arg name="age" value="23"/>
            <constructor-arg type="java.lang.String" value="  "/>
            <constructor-arg type="java.lang.String" value="173"/>
        </bean>
    </beans>
    
    
    ③ 실행 결과:
    在这里插入图片描述
    ⑤ 요약:
  • 무 참 구조 함수 지정 값 시 propert 태그
  • 사용
  • 참조 함수 지정 값 이 있 을 때 constructor-arg 태그,세 가지 쓰기
  • index-아래 표 시 를 통 해 속성 할당
  • name-속성 명 을 통 해 속성 할당
  • type-속성 을 지정 하 는 유형 으로 속성 에 값 을 부여 합 니 다.
  • 기본 유형 은
  • 을 직접 쓸 수 있다.
  • 인용 유형 은 전 칭 을 붙 여야 한다.예 를 들 어 java.lang.String
  • 위치 와 index 의 차이 가 많 지 않 고 위 에서 아래로 대응 하 는 속성 은 위 에서 아래로.
  • 프로필 을 불 러 올 때그 중 관리 대상 이 초기 화 되 었 습 니 다!
  • 3.Spring 의 설정
    3.1 alias(별명):
  • 은 bean 에 별명 을 설정 하고 여러 개 를 설정 할 수 있 습 니 다!
  • ①xml:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <alias name="Person" alias="personAlias1"/>
        <alias name="Person" alias="personAlias2"/>
        <alias name="Person" alias="personAlias3"/>
        <bean id="Person" class="entity.Person">
            <constructor-arg index="0" value="   "/>
            <constructor-arg name="age" value="23"/>
            <constructor-arg type="java.lang.String" value="  "/>
            <constructor-arg type="java.lang.String" value="173"/>
        </bean>
    </beans>
    
    
    ② 테스트 클래스:
    
    public class Test {
        public static void main(String[] args) {
            ApplicationContext Context = new ClassPathXmlApplicationContext("ContextAplication.xml");
            Person person = Context.getBean("personAlias1", Person.class);
            System.out.println(person);
        }
    }
    
    
    ③ 실행 결과:
    在这里插入图片描述
    ④ 결론:솔직히 이 물건 은 쓸모 가 많 지 않 습 니 다.별명 을 설정 하 는 더 좋 은 방법 이 있 기 때 문 입 니 다!
    3.2 Bean 의 설정:
  • bean 은 자바 대상 에 해당 하 며,Spring 에서
  • 을 만 들 고 관리 합 니 다.
    ①xml:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <alias name="Person" alias="personAlias1"/>
        <alias name="Person" alias="personAlias2"/>
        <alias name="Person" alias="personAlias3"/>
        <bean id="Person" name="person1,person2 person3;person4" class="entity.Person">
            <constructor-arg index="0" value="   "/>
            <constructor-arg name="age" value="23"/>
            <constructor-arg type="java.lang.String" value="  "/>
            <constructor-arg type="java.lang.String" value="173"/>
        </bean>
    </beans>
    
    
    ② 테스트 클래스:
    
    public class Test {
        public static void main(String[] args) {
            ApplicationContext Context = new ClassPathXmlApplicationContext("ContextAplication.xml");
            Person person = Context.getBean("person4", Person.class);
            System.out.println(person);
        }
    }
    
    
    ③ 실행 결과:
    在这里插入图片描述
    ④ 정리:
  • id 는 bean 의 유일한 식별 자
  • 설정 id 가 없 으 면 name 은 식별 자 에 해당 하 며 여러 개의
  • 을 설정 할 수 있 습 니 다.
  • name 도 별명 입 니 다.여러 개 가능 하 며 쉼표 빈 칸 으로 구분 할 수 있 습 니 다.alias 별명 보다 편리 하지 않 습 니까?그래서 별명 을 설정 할 때 저 희 는 보통 name
  • 을 사용 합 니 다.
  • id 와 name 이 동시에 존재 합 니 다.name 은 별명 일 뿐 식별 자
  • 이 아 닙 니 다.
  • class 는 클래스 의 전체 제한 이름 패키지+클래스 이름
  • 在这里插入图片描述
    3.3 import(팀워크 도입)
    ① 실제 작업 의 개발 과정 에서 하나의 프로젝트 는 여러 프로그래머 가 개발 할 수 있 기 때문에 공통성 문 제 를 해결 하기 위해 서 입 니 다.예 를 들 어 같은 파일 을 제출 할 때 수정 을 하면 충돌 을 일 으 킬 수 있 기 때문에 우 리 는 import 를 사용 하여 결합 을 해제 합 니 다!
    ② 여러 xml 프로필 을 새로 만 듭 니 다.
    在这里插入图片描述
    ContextAplication.xml:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <import resource="dyj1.xml"/>
        <import resource="dyj3.xml"/>
        <import resource="dyj2.xml"/>
    </beans>
    
    
    dyj1.xml:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean name="person1,person2 person3;person4" class="entity.Person">
            <constructor-arg index="0" value="   1"/>
            <constructor-arg name="age" value="23"/>
            <constructor-arg type="java.lang.String" value="  1"/>
            <constructor-arg type="java.lang.String" value="173"/>
        </bean>
    </beans>
    
    
    dyj2.xml:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean name="person1,person2 person3;person4" class="entity.Person">
            <constructor-arg index="0" value="   2"/>
            <constructor-arg name="age" value="23"/>
            <constructor-arg type="java.lang.String" value="  2"/>
            <constructor-arg type="java.lang.String" value="173"/>
        </bean>
    </beans>
    
    
    dyj3.xml:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean name="person1,person2 person3;person4" class="entity.Person">
            <constructor-arg index="0" value="   3"/>
            <constructor-arg name="age" value="23"/>
            <constructor-arg type="java.lang.String" value="  3"/>
            <constructor-arg type="java.lang.String" value="173"/>
        </bean>
    </beans>
    
    
    ③ 실행:
    在这里插入图片描述
    ④ 정리:
  • 만약 에 세 파일 이 모두 같은 조작 과 같은 종류 이거 나 내용 이 일치한다 면 주 xml 에서 위 에서 아래로 마지막 impot 를 기준 으로 한다.
  • 문법 형식:
  • 장점:
  • 모든 사람 이 개발 한 것 은 독립 적 인 것 입 니 다.중복 되 는 내용 이 있 으 면 Spring 은 자동 으로 합병 할 수 있 습 니 다!
  • 프로그램의 충돌 성 을 낮 추 었 습 니 다!
  • 은 후기 코드 의 유지 가능성 을 크게 향상 시 켰 습 니 다!
  • 총결산
    이 글 은 여기까지 입 니 다.당신 에 게 도움 이 되 기 를 바 랍 니 다.또한 당신 이 우리 의 더 많은 내용 에 관심 을 가 져 주 기 를 바 랍 니 다!

    좋은 웹페이지 즐겨찾기