springboot通过容器获取bean

一、写一个工具类

@Slf4j
@Component
public class ContextUtil implements ApplicationContextAware {
    private static ApplicationContext appCxt;

    @Override
    public void setApplicationContext(ApplicationContext appContext)// 交给spring容器管理 自动注入进来
            throws BeansException {
        if (appCxt == null) {
            appCxt = appContext;
        }
        log.info("ApplicationContext 对象初始化成功");
    }

    public static ApplicationContext getApplicationContext() {
        return appCxt;
    }

    //根据名称从spring容器中获取bean实例
    public static Object getBean(String beanName) {
        return appCxt.getBean(beanName);
    }

    //根据Java类型从Spring容器中获取bean实例
    public static <T> T getBean(Class<T> clazz) {
        return appCxt.getBean(clazz);
    }

    //根据名称和Java类型从Spring容器中获取bean实例
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return appCxt.getBean(beanName, clazz);
    }

}

二、写在启动上

@SpringBootApplication
public class SpringBootTest implements ApplicationContextAware {

    private static ApplicationContext context;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootTest.class, args);
        Object restTemplate = context.getBean("restTemplate");
        System.out.println(restTemplate);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context=applicationContext;
    }
}

你可能感兴趣的:(java,spring,boot,spring,java)