[SpringBoot 주해-3]Bean 주입 관련 주해
SpringBoot 에서 bean 의 주입 을 실현 하려 면 세 가지 주해 에 의존 합 니 다.
1 @Autowired
Spring Boot 응용 프로그램 이 시 작 될 때 Spring 용 기 는 org.springframework.beans.factory.annotation.autowired Annotation BeanPostProcessor 프로 세 서 를 자동 으로 불 러 옵 니 다.용기 가@Autowired 주 해 를 스 캔 할 때 IoC 용기 에서 해당 유형의 Bean 을 찾 아 주입 합 니 다.
1.1@Autowired 특징
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 와 대체적으로 같 고 다른 점 이 있 습 니 다.
예 는 다음 과 같다.
@Service
public class School{
@Resource(name = "teacher")
private Teacher teacher;
@Resource(type = Student.class)
private Student student;
public String toString(){
return teacher + "
" + student;
}
}
규칙 은 다음 과 같 습 니 다.
3 @Inject
간단 한 예제:
@Inject
@Named("BMW")
private Car car;
@Named 의 역할 은@Qualifier 와 유사 합 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Rails Turbolinks를 페이지 단위로 비활성화하는 방법원래 Turobolinks란? Turbolinks는 링크를 생성하는 요소인 a 요소의 클릭을 후크로 하고, 이동한 페이지를 Ajax에서 가져옵니다. 그 후, 취득 페이지의 데이터가 천이 전의 페이지와 동일한 것이 있...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.