springboot获取applicationcontext

使用springboot之前,我们通过ClassPathXmlApplicationContext加载spring xml配置文件来获取applicationcontext,使用springboot后,由于不存在xml文件,故该种方式已经不能使用

本例使用的为非web项目,在官方文档中介绍,可通过实现ApplicationRunner或者CommandLineRunner来执行非web项目,本例最初试图通过在实现以上两个接口方法中获取applicationcontext,

但未成功,@Order注解可设置实现以上两个接口的类启动顺序,但对含有main方法的springboot启动类无效,main方法的springboot启动类始终在最后执行

查看main方法中启动类代码

springboot获取applicationcontext

查看run方法,发现该方法返回ConfigurableApplicationContext

springboot获取applicationcontext

查看ConfigurableApplicationContext

springboot获取applicationcontext

接口实现了ApplicaitonContext接口,所以run方法返回的值就是我们需要的context了

 

启动类

package com.demo.Demo001;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
        ContextUtils.setApplicationContext(context);
        MainBusiEntry.execute();
    }
}

context工具类

package com.demo.Demo001;

import org.springframework.context.ApplicationContext;

public class ContextUtils {

    public static ApplicationContext context;

    private ContextUtils() {
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }
}

测试bean

package com.demo.Demo001;

import org.springframework.stereotype.Component;

@Component
public class TestBean {
    public String getName() {
        return this.getClass().getCanonicalName();
    }
}

业务处理入口

package com.demo.Demo001;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class MainBusiEntry {
    
    private static Logger logger = LogManager.getLogger(MainBusiEntry.class);
    public static void execute() {
        TestBean bean = ContextUtils.getBean(TestBean.class);
        logger.info(bean.getName());
    }
}

启动springboot,输出结果如下

  .   ____          _            __ _ _
 /\\ / ___‘_ __ _ _(_)_ __  __ _ \ \ \ ( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  ‘  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

11:53:25.302 INFO  org.springframework.boot.StartupInfoLogger.logStarting()/50 - Starting App on admin-PC with PID 195640 (D:\Programs\eclipseworkplace\springboot\Demo001\target\classes started by admin in D:\Programs\eclipseworkplace\springboot\Demo001)
11:53:25.338 INFO  org.springframework.boot.SpringApplication.logStartupProfileInfo()/675 - No active profile set, falling back to default profiles: default
11:53:26.375 INFO  com.mongodb.diagnostics.logging.SLF4JLogger.info()/71 - Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout=‘30000 ms‘, maxWaitQueueSize=500}
11:53:26.456 INFO  org.springframework.boot.StartupInfoLogger.logStarted()/59 - Started App in 1.393 seconds (JVM running for 2.078)
11:53:26.459 INFO  com.demo.Demo001.MainBusiEntry.execute()/11 - com.demo.Demo001.TestBean

输出了测试类的路径。

 

springboot获取applicationcontext

上一篇:Spring 3 来创建 RESTful Web Services


下一篇:利用Java反射机制完成XML到对象的解析