@ PostConstruct 주해 의 사용

4036 단어 Java
@ PostConstruct 는 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 의 설정 파일 에 관련 정 보 를 주입 한 다음 에 @PostConstructinit() 방법 이 실행 되 기 시 작 했 습 니 다. 시스템 유형 에 대한 판단 을 한 번 하고 imgDir 의 할당 을 완성 하여 FileTransferServiceImpl 호출 되 기 전에 imgDir 준비 가 완료 되 었 습 니 다. 더 이상 null 이 아 닙 니 다. 자 유 롭 게 호출 할 수 있 고 로드 순서 에 따 른 문 제 를 피 할 수 있 습 니 다.

좋은 웹페이지 즐겨찾기