본문 바로가기
spring

의존성 주입 (Dependency Injection), 어노테이션

by 신방동불주먹 2022. 12. 19.

1. 생성자 주입

 

  • 단일 생성자를 이용한 묵시적 주입

- 단일생성자 : 하나의 클래스에 하나의 생성자 (오버로딩x)

 

----------------annotation 설명------------------

  • @NonNull : null을 허용하지 않을 경우
  • @Nullable : null을 허용할 경우 
  • @RequiredArgsContstuctor : 특정한 변수에 대해서만 생성자를 작성하고 싶을 때 사용 , @notnull이나 final이 붙은 인스턴스 변수에 대한 생성자를 만들어 냄

 

2. Setter 메서드를 이용한 주입

 

예시)

 

@Component
@Data
public class Chef {
	
}
@Component
@Data
public class Restuarant {
	
	@Setter(onMethod_ = @Autowired)
	private Chef chef;

}

 

----------------annotation 설명------------------

 

  • @Component : 스프링에게 해당 클래스가 스프링에서 관리해야 하는 대상임을 표시 
  • @Setter : 자동으로 setChef()를 컴파일 시 생성

                       setter의 onMethod 속성은 setChef()에 @Autowired 어노테이션을 추가하도록 함

  • @Autowired :의존 객체의 타입에 해당하는 bean을 찾아 주입하는 역할
  • @Data : ToString, EqualsAndHashCode, Getter/Setter, RequiredArgsConstructor 모두 결합한 형태로 생성 

 src 내 - root-context.xml은 스프링에서 관리해야하는 객체를 의미 : Bean이라고 표현

 

 

-------------------------------------------------------

 

 

spring-test 모듈을 이용한 테스트 예시)

 

@RunWith(SpringJUnit4ClassRunner.class) //unit test 로 사용할거고 
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml") //요기서 필요한 정보 가져올거고
@Log4j//콘솔창에 log4j를 이용해 값을 찍어주는 기능
public class SampleTest {
	@Setter(onMethod_ = @Autowired) //만들어놓은 빈즈로 의존 주입이 자동으로 구현된다
	private Restuarant restaurant;
 
	@Test //실제로 test 진행 할거다 
	public void testExist() {
		assertNotNull(restaurant); //실제 있는 객체인지 확인. 정상적으로 나는지 
		log.info(restaurant);
		log.info("-----------------------------------------------------------");
		log.info(restaurant.getChef());
	}
}
//원래는 이렇게 작성했어야 할 것
//public void setRestaurant(Resturant restaurant){
 //this.restaurant = restaurant;
 //}

 

----------------annotation 설명------------------

  • @Runwith : 테스트 코드가 스프링을 실행하는 역할임을 의미
  • @ContextConfiguration : 필요한 객체를 스프링 내에 객체로 등록 (스프링 빈으로 등록)
  • 'classpath'나 'file'을 이용할 수 있으므로 이클립스에서 자동으로 생성된 root-context.xml 경로를 지정할 수 있음.
  • @Log4j : lombok을 이용해 로그를 기록하는 Logger를 변수로 생성. 별도 객체 선언 불필요
  • @Test : JUnit 에서 해당 메서드가 단위테스트의 대상인지를 판단

 ----------------속성 설명------------------

  • assertNotNull()  : retaurant 변수가 null이 아니여야 테스트가 가능하다.

 

'spring' 카테고리의 다른 글

bean 등록방식  (0) 2022.12.20
JDBC연결 ( jdbc6.jar 설치) 필수3  (0) 2022.12.20
파일 역할 정의  (0) 2022.12.19
스프링 동작 순서  (0) 2022.12.19
뭔지 몰라  (0) 2022.12.19