IT

Spring @PostConstruct vs. init-method 속성

itgroup 2023. 2. 27. 22:52
반응형

Spring @PostConstruct vs. init-method 속성

를 사용하는 것과 다른 점이 있습니까?@PostConstruct주석과 같은 방법을 선언합니다.init-methodSpring XML 구성 중?

아니요, 실질적으로 저는 차이가 없다고 생각하지만 그들이 일하는 방식에는 우선순위가 있습니다. @PostConstruct,init-methodBean Post Processors 입니다.

  1. @PostConstructJSR-250 주석입니다.init-methodSpring의 초기화 방식입니다.
  2. 를 가지고 있는 경우@PostConstructmethod. 초기화 메서드를 호출하기 전에 먼저 호출됩니다.
  3. 빈이 InitializingBean을 구현하여 재정의하는 경우afterPropertiesSet,첫번째@PostConstruct호출된 후afterPropertiesSet그리고 나서.init-method.

자세한 내용은 Spring의 참조 문서를 참조하십시오.

JSR 250 사양 이전에는 xml에서의 init-method 사용이 권장되었습니다.이는 Java 클래스(빈)를 스프링 고유의 클래스 또는 주석에서 분리하기 때문입니다.따라서 스프링 인프라스트럭처의 콩에 의존할 필요가 없는 라이브러리를 구축할 경우 init-method를 사용하는 것이 좋습니다.작성 방법에서는 초기화 방법으로 호출해야 하는 방법을 지정할 수 있습니다.

Java EE에서 JSR 250 사양이 도입되고 이러한 주석이 스프링으로 지원됨에 따라 스프링 프레임워크에 대한 의존도가 어느 정도 낮아졌습니다.

하지만 이것들을 추가하면 코드의 가독성이 높아진다는 것은 인정해야 합니다.그래서 두 가지 접근법 모두 장단점이 있습니다.

진짜 차이는 없어요.시스템 구성 방법에 따라 다르며, 이는 개인의 선택에 달려 있습니다.나 자신, 나는 이 제품을 사용하는 것을 선호한다.@PostConstructmy code에 대한 주석(메서드가 호출된 후에만 bean이 올바르게 구성되기 때문에)을 사용하여init-method스프링을 지원하지 않는 라이브러리에서 콩을 인스턴스화할 때(물론 거기에 주석을 적용할 수는 없습니다!) 하지만 저는 어떤 식으로든 모든 것을 원하는 사람들을 완전히 이해할 수 있습니다.

@postconstructure는 스프링의 일부가 아닙니다.javax 패키지의 일부입니다.둘 다 똑같아요.init-module을 사용하여 xml 파일에 추가해야 합니다.@postconstruct를 사용하는 경우 xml에서 추가할 필요가 없습니다.다음 문서를 참조하십시오.

http://answersz.com/spring-postconstruct-and-predestroy/

풀코드 : https://github.com/wkaczurba/so8519187 (스프링 부트)

주석 사용:

@Slf4j
@Component
public class MyComponent implements InitializingBean {

    @Value("${mycomponent.value:Magic}")
    public String value;

    public MyComponent() {
        log.info("MyComponent in constructor: [{}]", value); // (0) displays: Null
    }

    @PostConstruct
    public void postConstruct() {
        log.info("MyComponent in postConstruct: [{}]", value); // (1) displays: Magic
    }

    @Override // init-method; overrides InitializingBean.afterPropertiesSet()
    public void afterPropertiesSet() {
        log.info("MyComponent in afterPropertiesSet: [{}]", value);  // (2) displays: Magic
    }   

    @PreDestroy
    public void preDestroy() {
        log.info("MyComponent in preDestroy: [{}]", value); // (3) displays: Magic
    }
}

다음 정보를 입수합니다.

org.springframework.context를 새로 고치는 중...

[]([null MyComponent: [null]
[ my my component내 컴포넌트: [Magic]
in after Properties after Properties my My Component Set : [ Magic] : [ ]


시 을 위한 콩 중(Registering for JMX
0에 Demo 이 1.동안 중) 0.561 Demo Application(JVM 1.011)
orgorg.springframework.context...Unregistering on shutdown( 시 JMX 노출 콩 등록 )


in preDestroy : [ ]PreDestroy 마이 컴포넌트 : [ Magic ]

아래 그림에서 볼 수 있듯이 Bean Creation Life-Cycle Callback은 다음과 같습니다.

Bean Creation 라이프 사이클 콜백

Bean Creation Life-Cycle 콜백에서는 다음 3단계를 수행합니다.

  1. 라고 되어 있다@PostConstruct출됩니니다다
  2. ifInitializingBean이 되고 실행이 됩니다.afterPropertiesSet()출됩니니다다
  3. 에 콩이 포함되어 있는 init-method ★★★★★★★★★★★★★★★★★」@Bean(initmethod="..") 다음 methodinit을 합니다.

이 그림은 Pro Spring 5: Spring Framework 도구 상세 가이드에서 인용한 것입니다.

와는 차이가 있을 수 있습니다.@PostConstruct ★★★★★★★★★★★★★★★★★」init-method@PostConstruct에서 처리됩니다.postProcessAfterInitialization단계(콩 초기화 단계)AbstractAutowireCapableBeanFactory.initializeBean() by 'method' (메서드)CommonAnnotationBeanPostProcessor와 동시에 , 「」를 참조해 주세요.init method 가 완료되면 됩니다.postProcessBeforeInitialization는, 「」의 postProcessAfterInitialization★★★★★★★★★★★★★★★★★★」
편집: 이 순서는 다음과 같습니다.1 )postProcessBeforeInitialization2) )계, 2)init)postProcessAfterInitialization하는 단계, 「」@PostConstruct

(부록으로서 승낙한 답변의 진술.

@PostConstruct, init-method는 BeanPostProcessors입니다.

@PostConstruct에 의해 처리됩니다.BeanPostProcessor,init방법이 아닙니다.)

일부(잠재적으로는 커스텀)의 경우 차이가 있습니다.BeanPostProcessor ( )로 .Ordered.getOrder()CommonAnnotationBeanPostProcessor님은 그 안에서 뭔가 중대한 일을 하고 있습니다.postProcessBeforeInitialization★★★★★★ 。
의 기본 스프링 설정과 차이가 없습니다.BeanPostProcessors 모든 이 다BeanPostProcessors which which 、 which which 、 음 which 、 which which 、 which which 、 which which which which which which 。CommonAnnotationBeanPostProcessor에서는 아무것도 하지 postProcessBeforeInitialization★★★★★★ 。

결론적으로, 인정된 답변과 비슷한 답변이 맞다...99%의 경우, 이 게시물은 단지 "상세정보에 정보가 있다"라는 개념에 경의를 표하기 위한 것입니다.

언급URL : https://stackoverflow.com/questions/8519187/spring-postconstruct-vs-init-method-attribute

반응형