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