学无先后,达者为师

网站首页 编程语言 正文

SpringBoot手动获取实例

作者:@yiyi123 更新时间: 2023-10-31 编程语言

1.首先创建一个接口里面是关于建库建表的方法

public interface MetaMapper {
    //三个核心建表方法
    void createExchangeTable();
    void createQueueTable();
    void createBingdingTable();
}

2.启动类中定义一个ConfigurableApplicationContext 类型的变量context接收SpringApplication.run(MqApplication.class, args)的返回值

public class MqApplication {
    //手动获取metaMapper实例
    public static ConfigurableApplicationContext context;

    public static void main(String[] args) {
       context = SpringApplication.run(MqApplication.class, args);
    }
}

在查看SpringApplication.run()方法的源码时发现返回的也是ConfigurableApplicationContext 类型的值

  public static ConfigurableApplicationContext run(Class<?> primarySource, 
String... args) {
        return run(new Class[]{primarySource}, args);
    }

3.metaMapper变量通过启动类中context的getBean方法进行实例化,里面的参数是需要实例化的类。之后就可以使用metaMapper中的方法了。

public class DataBaseManager {
    private MetaMapper metaMapper;

    //针对数据库进行初始化
    public void init(){
        //手动获取到metaMapper
        metaMapper = MqApplication.context.getBean(MetaMapper.class);
}

原文链接:https://blog.csdn.net/qq_51866806/article/details/134044230

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新