14、生命周期-@PostConstruct&@PreDestroy

  • @PostConstruct 在Bean创建完并且属性值赋值完执行
package javax.annotation;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}

  • @PreDestroy 在Bean销毁之前
package javax.annotation;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PreDestroy {
}

14.1 创建Dog实例

package com.hw.springannotation.beans;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Description TODO
 * @Author hw
 * @Date 2018/11/28 19:53
 * @Version 1.0
 */
@Component
public class Dog {
    public Dog() {
        System.out.println("Dog construct....");
    }

    @PostConstruct
    public void initDog() {
        System.out.println("Dog PostConstruct.....");
    }

    @PreDestroy
    public void destroyDog() {
        System.out.println("Dog PreDestroy....");
    }
}

14.2 运行