fans:https://www.cnblogs.com/chenpi/p/9785938.html

通过 CommandLineRunner 接口,可以实现在 Spring Boot 完全启动后执行一些代码逻辑,本文将执行的逻辑是打印所有 Bean 的信息;

  1. 通过 ApplicationContext.getBeanDefinitionNames() 方法获取所有 Bean 的名称;
  2. 通过 ApplicationContext.getBean(beanName) 获取 Bean 的详细信息;
package com.cy;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootApplication
public class BlogApplication implements CommandLineRunner {

	public static void main(String[] args) {
		ConfigurableApplicationContext applicationContext = SpringApplication.run(BlogApplication.class, args);
		log.info("===================================启动完毕==================================");
	}
	
	@Autowired
	private ApplicationContext applicationContext  ; 

	/* * implements CommandLineRunner * 项目启动完成后 执行 * */
	@Override
	public void run(String... args) throws Exception {
		String[] names = applicationContext.getBeanDefinitionNames();
		int index = 1 ; 
		for (String name : names) {
			log.info("{}: {}", index++ , name );
		}
		log.info("项目启动 容器注入javaBean:{}个.",names.length);
	}

}

运行以上程序,控制台将打印如下信息: