spring boot 啟動 開啟注解 加載 bean


業務描述:創建一個cache類然后交給spring 管理。

 

@Component

@Scope("singleton")

public class Cache {

 

    public Cache() {

       System.out.println("cache()");

    }

    @PostConstruct

    public void init() {

        System.out.println("init()");

    }

    @PreDestroy

    public void destory() {

        System.out.println("destory");

    }

}

 

 

 

 

 

 

 

 

修改sringboot 啟動類,進行bean的獲取及測試。

 

package com.cy;

@SpringBootApplication

public class CgbSpringbootApplication implements ApplicationContextAware {

    private static AnnotationConfigApplicationContext ctx;

    @Override

    public void setApplicationContext(ApplicationContext

applicationContext) throws BeansException {

      ctx=(AnnotationConfigApplicationContext)applicationContext;

    }

    public static void main(String[] args) {

        SpringApplication.run(CgbSpringbootApplication.class, args);

        System.out.println(ctx.getBean("cache"));

        System.out.println(ctx.getBean("cache"));

        ctx.close();

       

    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM