@PostConstruct和@PreDestroy是兄弟

@PostConstruct

注解的方法在构造方法执行完之后执行。

@PreDestroy

注解的方法在Bean销毁之前执行

注意:这两个方法修饰的一定是非静态的void方法,并且Constructor >> @Autowired >> @PostConstruct

话不多说,上代码

package com.springboot.gyh.ch2.prepost;


public class BeanWayService {

    public void init(){
        System.out.println("@Bean-init-method");
    }

    public BeanWayService(){
        super() ;
        System.out.println("初始化构造函数-BeanWayService");
    }

    public void destroy(){
        System.out.println("@Bean-destroy-method");
    }

}

package com.springboot.gyh.ch2.prepost;

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

public class JSR250WayService {

    @PostConstruct
    public void init(){
        System.out.println("jsr250-init-method");
    }

    public JSR250WayService(){
        System.out.println("初始化构造函数-JSR250WayService");
    }

    @PreDestroy
    public void destroy(){
        System.out.println("jsr250-destroy-method");
    }

}

package com.springboot.gyh.ch2.prepost;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.springboot.gyh.ch2.prepost")
public class PrePostConfig {

    @Bean(initMethod = "init" , destroyMethod = "destroy")
    BeanWayService beanWayService(){
        return new BeanWayService() ;
    }

    @Bean(initMethod = "init" , destroyMethod = "destroy")
    JSR250WayService jsr250WayService(){
        return new JSR250WayService() ;
    }
}

package com.springboot.gyh.ch2.prepost;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class) ;

        BeanWayService beanWayService = context.getBean(BeanWayService.class) ;

        JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class) ;

        context.close();
    }
}

发布了56 篇原创文章 · 获赞 3 · 访问量 1180

猜你喜欢

转载自blog.csdn.net/qq_40788718/article/details/103338018