POM
라는 프로젝트 만들기 hello-spring
프로젝트 pom.xml
는 다음과 같이 파일 :
1 <? XML 버전 = "1.0" "UTF-8"인코딩 = " 2 "를 http://maven.apache.org/POM/4.0.0 "= <프로젝트에 xmlns 3 개 에 xmlns :이 xsi ="HTTP : // www.w3.org/2001/XMLSchema-instance " 4 XSI :의 schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0 .XSD "> 5 <modelVersion> 4.0.0 </ modelVersion> 6 7 <의 groupId> com.snake </의 groupId> 8 <artifactId를> 헬로 스프링 </ artifactId를> 9 <버전> 1.0.0-SNAPSHOT </ 버전 > 10 <포장> 단지 </ 포장> 11 12 < 의존성> 13 <의존성> 14 <의 groupId> org.springframework </의 groupId> 15 <artifactId를> 스프링 컨텍스트 </ artifactId를> 16 <버전> 4.3.17.RELEASE </ 버전> 17 </ 의존성> 18 </ 의존성> 19 </ 프로젝트>
인터페이스 및 구현 만들기
# 만들기의 UserService
인터페이스
1 패키지 com.snake.hello.spring.service; 2 3 공중 인터페이스 UserService { 4 공개 공극 sayHi (); 5 }
만들기 UserServiceImpl
달성
패키지 com.snake.hello.spring.service.impl을; 수입 com.snake.hello.spring.service.UserService; 공공 클래스 UserServiceImpl의 구현의 UserService { 공공 무효 sayHi () { 에서 System.out.println ( "안녕하세요 봄" ); } }
# Spring 설정 파일을 작성
에서 src/main/resources
디렉토리 만들기 spring-context.xml
지금부터, 프로파일 스프링 컨테이너 관리 (IOC의)에 대한 클래스 작업을 인스턴스화, 구성 파일은 다음과 같습니다 :
<? XML 버전 = "1.0" "UTF-8"인코딩 =?> <콩의 xmlns = "http://www.springframework.org/schema/beans" XMLNS : XSI = "http://www.w3.org/2001/XMLSchema-instance" XSI :의 schemaLocation = " HTTP : // WWW .springframework.org / 스키마 / 콩 http://www.springframework.org/schema/beans/spring-beans.xsd "> <콩 ID = "userService" 클래스 = "com.funtl.hello.spring.service.impl.UserServiceImpl"/> </ 콩>
-
<bean />
: 객체의 인스턴스를 정의하는 데 사용됩니다. 빈 요소 대응의 한 예. -
id
이 속성은 빈의 id 속성 콩, 콩 의존성도 id 속성과 연관된 액세스에 고유 한 식별자 Bean 인스턴스이다. -
class
: 콩은 클래스가 아닌 인터페이스 할 수있다 여기에 지정된 클래스, 임금의 관심에 속한다.
# 테스트 스프링의 IoC
크리에이트 MyTest
스프링에 의해 테스트 개체가, 코드가 다음과 같다 경우 테스트 클래스를 생성 할 수 있습니다 :
패키지 com.snake.hello.spring; 수입 com.snaek.hello.spring.service.UserService; 수입 org.springframework.context.ApplicationContext; 수입 org.springframework.context.support.ClassPathXmlApplicationContext; 공공 클래스 MYTEST { 공공 정적 무효 메인 (문자열 []에 args) { // 获取스프링容器 ApplicationContext의 애플리케이션 컨텍스트 = 새로운 ClassPathXmlApplicationContext ( "스프링의 context.xml" ); // 컨테이너 봄에서 개체 가져 applicationContext.getBean ( "그 userService"에 UserService 그 userService = (UserService를) ); userService.sayHi (); } }