2019. 4. 26. 16:00ㆍSpring
#1) Spring legacy project의 기본 구조
여기서 webapp은 jsp의 webcontent와 같은 역할을 한다.
#2) XML을 이용하는 의존성 주입 설정
스프링은 클래스에서 객체를 생성하고 객체들의 의존성에 대한 처리 작업까지 내부에서 모든 것이 처리된다.
스프링에서 관리되는 객체를 흔히 '빈(Bean)'이라한다.
root-context.xml은 스프링 프레임워크에서 관리해야 하는 객체를 설정하는 파일이다.
Namespaces에서 context를 체크한다.
#3) spring 의존성 설정
#4) 코드
<?xml version="1.0" encoding="UTF-8"?> <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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.exam.sample"> </context:component-scan> </beans> |
- Chef.java
package com.exam.sample;
import org.springframework.stereotype.Component;
@Component public class Chef {
}//Chef |
- Restaurant.java
package com.exam.sample;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
import lombok.Data; import lombok.Setter;
@Component @Data public class Restaurant { @Setter(onMethod_ = @Autowired) private Chef chef;
// public Chef getChef() { // return chef; // } // @Autowired //의존관계주입 // public void setChef(Chef chef) { // this.chef = chef; // }
}//Restaurant |
- Ex1.java
package com.exam.sample;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Ex1 {
public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("sample-context.xml", Ex1.class);
// 애노테이션 @Autowired 가 필요한 객체를 찾는 방식 // 1) 컨텍스트객체(컨테이너)안에서 해당 타입으로 찾는다. // 2) 해당 타입이 없으면 해당 이름으로 찾는다. Restaurant r = (Restaurant) applicationContext.getBean(Restaurant.class); // Restaurant r = (Restaurant)applicationContext.getBean("restaurant");
Chef chef = r.getChef(); System.out.println(r); System.out.println(chef); }// main
} |
'Spring' 카테고리의 다른 글
pom.xml 설정하기 (0) | 2019.11.21 |
---|