[SpringBoot 주해-3]Bean 주입 관련 주해

흔히 볼 수 있 는 주해 총결산 의 Bean 주입
  • 1 @Autowired
  • 1.1@Autowired 특징
  • 1.2 사용 예시
  • 1.2 흔 한 이상
  • 2 @Resource
  • 3 @Inject

  • SpringBoot 에서 bean 의 주입 을 실현 하려 면 세 가지 주해 에 의존 합 니 다.
  • @Autowired
  • @Inject
  • @Resource

  • 1 @Autowired
    Spring Boot 응용 프로그램 이 시 작 될 때 Spring 용 기 는 org.springframework.beans.factory.annotation.autowired Annotation BeanPostProcessor 프로 세 서 를 자동 으로 불 러 옵 니 다.용기 가@Autowired 주 해 를 스 캔 할 때 IoC 용기 에서 해당 유형의 Bean 을 찾 아 주입 합 니 다.
    1.1@Autowired 특징
  • @Autowired 가 Spring 에 제공 하 는 주 해 는 패키지 org.springframework.beans.factory.annotation.autowired
  • 를 가 져 와 야 합 니 다.
  • @Autowired 주 해 는 형식(by Type)에 따라 의존 대상 을 조립 하 는 것 입 니 다.기본적으로 의존 대상 이 존재 해 야 합 니 다.null 값 을 허용 하면 required 속성 을 false 로 설정 할 수 있 습 니 다.이름(by Name)에 따라 설치 하려 면@Qualifier 주석 과 함께 사용 할 수 있 습 니 다.

  • 1.2 사용 예시
    MVC 모드 에서 제어 층(controller)이 업무 층(service)에 주입 하려 면@Autowired 를 사용 해 야 합 니 다.다음 과 같 습 니 다.
    //    
    @RestController
    @RequestMapping(value = "/test")
    public class CaseController {
        @Autowired
        private TestService testService;
    
        @RequestMapping(value = "/autowired", method = RequestMethod.GET)
        public int test() {
            return testService.test();
        }
    }
    
    //    
    @Service
    public interface CaseService {
        int test();
    }
    
    //      
    @Service(value = "testService")
    public class CaseServiceImpl implements CaseService {
    	@Override
    	public int test(){
    		return 1;
    	}
    }
    

    1.2 흔 한 이상
    이상 장면 1:인터페이스 에 클래스 가 없습니다.Spring Boot 응용 프로그램 을 시작 하면 다음 과 같은 오류 가 발생 합 니 다.
    Description:
    
    Field interfaceTest in com.ui.InterfaceController required a bean of type 'com.ui.InterfaceTest' that could not be found.
    
    The injection point has the following annotations:
    	- @org.springframework.beans.factory.annotation.Autowired(required=true)
    
    Action:
    
    Consider defining a bean of type 'com.ui.InterfaceTest' in your configuration.
    
    Process finished with exit code 1
    

    오류 메시지 에서 볼 수 있 습 니 다.@Autowired 에 required=false 를 추가 하면 됩 니 다.
    @RestController
    public class InterfaceController {
        @Autowired(required = false)
        private InterfaceTest interfaceTest;
    
        @RequestMapping(value = "/test", method = RequestMethod.GET)
        public int getCaseList() {
            return interfaceTest.getCount();
        }
    }
    

    프로젝트 가 정상적으로 시 작 될 수 있 습 니 다.물론 이 controller 를 호출 할 때 빈 포인터 이상 을 알 립 니 다.
    java.lang.NullPointerException: null
        at com.ui.InterfaceController.get(TestServiceImpl.java:23) ~[classes/:na]
        at com.ui.InterfaceController.get(TestController.java:18) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_60]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_60]
    

    이상 장면 2:인터페이스 에 여러 개의 실현 클래스 가 존재 합 니 다.인터페이스 에 여러 개의 실현 클래스 가 존재 할 때 다음 과 같은 특수 처 리 를 해 야 합 니 다.@Autowired 에서 required 속성 을 false 로 설정 합 니 다.즉,SpringBoot 가 해당 Bean 과 일치 하지 않 을 때 도 오 류 를 보고 하지 마 십시오.**@Qualifier**에서 주입 할 실현 클래스(주입 하고 싶 은 클래스 와 같 고 이니셜 소문 자)를 지정 합 니 다.다음 과 같 습 니 다.
    // TestService      
    @Service(value = "testService")
    public class testServiceImplSecond implements testService {
    	@Override
    	public int test(){
    		return 2;
    	}
    }
    
    //      testService,        
    @RestController
    @RequestMapping(value = "/test")
    public class CaseController {
        @Autowired(required = false)
    	@Qualifier("testServiceSecond")
        private TestService testService;
    
        @RequestMapping(value = "/autowired", method = RequestMethod.GET)
        public int test() {
            return testService.test();
        }
    }
    

    2 @Resource
    @Resource 의 역할 은@Autowired 와 대체적으로 같 고 다른 점 이 있 습 니 다.
  • @Autowired 는 Spring 의 주석 이 고,@Resource 는 J2EE 의 주석 이 며,주석 을 가 져 온 가방 이름 에 따라 알 수 있 습 니 다.-@Autowired 는 기본적으로 byType 방식 으로 bean 매 칭 을 하고,@Resource 는 기본적으로 byName 방식 으로 bean 매 칭 을 합 니 다
  • Spring 은 제3자 에 속 하고 J2EE 는 자바 자신의 것 이다.따라서 코드 와 Spring 간 의 결합 을 줄 이기 위해@Resource 주 해 를 사용 하 는 것 을 권장 합 니 다.
  • @Autowired 는 constructor,method,parameter,field,annotation 에 작용 할 수 있 습 니 다.type 에서@Resource 는 method,field,type 에 작용 할 수 있 습 니 다.

  • 예 는 다음 과 같다.
    @Service
    public class School{
        @Resource(name = "teacher")
        private Teacher teacher;
        @Resource(type = Student.class)
        private Student student;
        public String toString(){
            return teacher + "
    "
    + student; } }

    규칙 은 다음 과 같 습 니 다.
  • @Resource 뒤에 내용 이 없습니다.기본적으로 name 속성 을 통 해 bean 과 일치 합 니 다.type 으로 일치 하 는 것 을 찾 을 수 없습니다.
  • name 이나 type 을 지정 하면 지정 한 형식 에 따라 bean 과 일치 합 니 다.
  • name 과 type 을 지정 하면 지정 한 name 과 type 에 따라 bean 과 일치 합 니 다.일치 하지 않 으 면 오류 가 발생 합 니 다.

  • 3 @Inject
  • @Inject 는 JSR 330(Dependency Injection for Java)의 규범 으로 javax.inject.Inject jar 패 키 지 를 가 져 와 야 주입 이 가능 합 니 다.
  • @Inject 는 constructor,method,field 에 작용 할 수 있 습 니 다.
  • @Inject 는 유형 에 따라 자동 으로 조립 되 며,이름 에 따라 조립 해 야 할 경우@Named 에 맞 춰 야 합 니 다.

  • 간단 한 예제:
    @Inject
    @Named("BMW")
    private Car car;
    

    @Named 의 역할 은@Qualifier 와 유사 합 니 다.

    좋은 웹페이지 즐겨찾기