@ PostConstruct 주해 의 사용
4036 단어 Java
javax.annotation
패키지 의 주석 중 하나 이 며, 원본 주석 은 다음 과 같 습 니 다.The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependencyinjection. The method annotated with PostConstruct MUST be invoked even if the class does not request any resources to be injected. Only one method can be annotated with this annotation…
요약 하면 그 역할 은 주입 에 의존 한 후 대상 의 비 정적
void
방법 에서 특정 임 무 를 수행 하여 대상 이 사용 하기 전에 임 무 를 수행 할 수 있 도록 하 는 것 이다.묘사 가 추상 적일 수 있 으 니 Spring Boot 프로젝트 의 간단 한 예 로 설명 하 세 요.
사례:
개발 초기 에는 윈도 시스템 컴퓨터 를 이용 해 개발 하고 가끔 서버 에서 테스트 를 하 며 파일 을 저장 할 때 경로 문제 와 관련 이 있 는데 윈 과 리 눅 스 경로 가 일치 하지 않 기 때문에 서로 다른 테스트 경 로 를 설정 해 야 한다.예 를 들 어 그림 업로드 테스트 는
.yml
테스트 파일 의 설정 이 다음 과 같 습 니 다....
picture:
linuxDir: /tmp/img_test
winDir: C:\Users\dash\img_test
그림 업로드 서 비 스 를 실행 할 때 어떤 경 로 를 사용 할 지 결정 해 야 합 니 다.시스템 이 실 행 된 후에 한 번 에 시스템 유형 을 판단 하고 적당 한 경 로 를 선택 하기 위해 다음 과 같은 코드 로 실현 할 수 있 습 니 다.
public class FileTransferServiceImpl implements FileTransferService {
@Value("${picture.linuDir}")
private String linuxImgDir;
@Value("${picture.winDir}")
private String winImgDir;
private String imgDir;
@PostConstruct
public void init() {
imgDir = linuxImgDir;
if (!OsUtils.isLinx()) {
imgDir = winImgDir;
}
}
...
}
@Value
Spring Boot 의 설정 파일 에 관련 정 보 를 주입 한 다음 에 @PostConstruct
의 init()
방법 이 실행 되 기 시 작 했 습 니 다. 시스템 유형 에 대한 판단 을 한 번 하고 imgDir 의 할당 을 완성 하여 FileTransferServiceImpl
호출 되 기 전에 imgDir 준비 가 완료 되 었 습 니 다. 더 이상 null 이 아 닙 니 다. 자 유 롭 게 호출 할 수 있 고 로드 순서 에 따 른 문 제 를 피 할 수 있 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.