具有自定义ApplicationContext实现的Spring启动应用程序

时间:2017-06-16 16:30:00

标签: java spring spring-boot

我有一个基于Spring框架的应用程序。为了实现一些要求,我必须提供我自己的ApplicationContext

实现

现在我搬到了spring-boot我想知道是否有办法强制启动使用我ApplicationContext的实现?

编辑:提供一些代码

public class OpenPatricianSpringBootStandaloneApplication implements CommandLineRunner {
    private static Logger logger = LogManager.getLogger(OpenPatricianSpringBootStandaloneApplication.class);

    public static void main(String[] args) throws Exception {
        SpringApplication.run(OpenPatricianSpringBootStandaloneApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        String jreVersion = (String) System.getProperties().get("java.version");
        if (!jreVersion.startsWith("1.8")) {
            logger.error("JRE must be of version 1.8");
            System.out.println("JRE must be of version 1.8");
            System.exit(1);
        }
        logEnvironment();
        CommandLineArguments cmdHelper = new CommandLineArguments();
        Options opts = cmdHelper.createCommandLineOptions();
        CommandLine cmdLine = cmdHelper.parseCommandLine(opts, args);
        if (cmdLine.hasOption(CommandLineArguments.HELP_OPTION)){
            cmdHelper.printHelp(opts);
            System.exit(0);
        }
        if (cmdLine.hasOption(CommandLineArguments.VERSION_OPTION)) {
            System.out.println("OpenPatrician version: "+getClass().getPackage().getImplementationVersion());
            System.exit(0);
        }
        cmdHelper.persistAsPropertyFile(cmdLine);

        unpackPlugins();

        ServerLauncher.initializeApplicationContext(StandaloneConfiguration.class);
        OpenPaticianApplicationWindow.startClientUI(new String[0]);
    }

在最后一行创建上下文:

public static void initializeApplicationContext(Class clientServerContextClass) {
    Preconditions.checkArgument(baseServerContext == null, "Application baseServerContext is already initialized");
    baseServerContext =  new DependentAnnotationConfigApplicationContext(clientServerContextClass);
    logger.info("Initialize baseServerContext (" + baseServerContext.hashCode() + ") with class "+clientServerContextClass.getName());
    ((AbstractApplicationContext)baseServerContext).registerShutdownHook();

}

DependentAnnotationConfigApplicationContext是我正在使用的ApplicationContext实施。这就是如何在没有弹簧启动的情况下创建spring applicationn。

1 个答案:

答案 0 :(得分:-1)

有一个可以实现的接口ApplicationListener,它接受许多监听器,如Refresh,Start。

public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    ApplicationContext applicationContext = event.getApplicationContext();
    // now you can do applicationContext.getBean(...)
    // ...
}

}

希望这会有所帮助。