Example usage for org.springframework.context ConfigurableApplicationContext getAutowireCapableBeanFactory

List of usage examples for org.springframework.context ConfigurableApplicationContext getAutowireCapableBeanFactory

Introduction

In this page you can find the example usage for org.springframework.context ConfigurableApplicationContext getAutowireCapableBeanFactory.

Prototype

AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;

Source Link

Document

Expose AutowireCapableBeanFactory functionality for this context.

Usage

From source file:com.github.bfour.fpliteraturecollector.application.Application.java

public static void main(String[] args) {

    try {//from   w w  w  .  ja  v  a2 s  . com

        // https://vvirlan.wordpress.com/2014/12/10/solved-caused-by-java-awt-headlessexception-when-trying-to-create-a-swingawt-frame-from-spring-boot/
        SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
        builder.headless(false);
        ConfigurableApplicationContext context = builder.run(args);

        // Neo4jResource myBean = context.getBean(Neo4jResource.class);
        // myBean.functionThatUsesTheRepo();

        // ServiceManager servMan = ServiceManager
        // .getInstance(ServiceManagerMode.TEST);
        ServiceManager servMan = context.getBean(ServiceManager.class);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(servMan,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);

        FPJGUIManager.getInstance().initialize();

        MainWindow.getInstance(servMan).setVisible(true);

    } catch (BeanCreationException e) {
        e.printStackTrace();
        if (ExceptionUtils.getRootCause(e) instanceof IOException)
            ApplicationErrorDialogue.showMessage("Sorry, could not access the database.\n"
                    + "This might be because it is currently in use or because there are insufficient access rights.\n"
                    + "Try closing all running instances of this application and restart.");
        else
            ApplicationErrorDialogue.showDefaultMessage(e, BUG_REPORT_URL);
    } catch (Exception e) {
        e.printStackTrace();
        ApplicationErrorDialogue.showDefaultMessage(e, BUG_REPORT_URL);
    }

}

From source file:org.onebusaway.nyc.vehicle_tracking.utility.SensorModelVerificationMain.java

public static void main(String[] args)
        throws ParseException, ClassNotFoundException, CsvEntityIOException, IOException {

    Options options = new Options();
    options.addOption(ARG_RULE, true, "sensor model rule class");
    GnuParser parser = new GnuParser();
    CommandLine cli = parser.parse(options, args);

    args = cli.getArgs();/* ww  w  .  j  a  v  a 2  s .  c om*/

    if (args.length != 2) {
        System.err.println("usage: data-sources.xml tracesPath");
        System.exit(-1);
    }

    ConfigurableApplicationContext context = ContainerLibrary.createContext(
            "classpath:org/onebusaway/nyc/vehicle_tracking/application-context.xml",
            "classpath:org/onebusaway/transit_data_federation/application-context.xml", args[0]);

    SensorModelVerificationMain m = new SensorModelVerificationMain();
    context.getAutowireCapableBeanFactory().autowireBean(m);

    Collection<SensorModelRule> rules = Collections.emptyList();

    if (cli.hasOption(ARG_RULE)) {
        Class<?> ruleClass = Class.forName(cli.getOptionValue(ARG_RULE));
        rules = Arrays.asList((SensorModelRule) context.getBean(ruleClass));
    } else {
        Map<String, SensorModelRule> rulesByName = context.getBeansOfType(SensorModelRule.class);
        rules = rulesByName.values();
    }

    m.setRules(rules);

    File tracePath = new File(args[1]);
    List<File> traces = new ArrayList<File>();
    getAllTraces(tracePath, traces);
    m.setTraces(traces);

    try {
        m.run();
    } catch (Throwable ex) {
        ex.printStackTrace();
        System.exit(-1);
    }

    System.exit(0);
}

From source file:org.echocat.jomon.spring.testing.environments.BeanEnvironment.java

protected void autowire(@Nonnull ConfigurableApplicationContext applicationContext, @Nonnull Object bean) {
    final AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext
            .getAutowireCapableBeanFactory();
    autowireCapableBeanFactory.autowireBean(bean);
}

From source file:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java

/**
 * Batch Job? .//www  .j a  v  a  2  s. c  o m
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        context = new ClassPathXmlApplicationContext(jobPath);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        // Batch Job? .
        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // ? Batch Job? ? abandon .
        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // Batch Job? .
        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("EgovCommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        EgovCommandLineRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:lcn.module.batch.core.launch.support.CommandLineRunner.java

/**
 * Batch Job? .//from  www  . j a  va 2s.c  o  m
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        context = new ClassPathXmlApplicationContext(jobPath);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        // Batch Job? .
        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // ? Batch Job? ? abandon .
        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // Batch Job? .
        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("CommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        CommandLineRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:org.springframework.batch.core.launch.support.CommandLineJobRunner.java

@SuppressWarnings("resource")
int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {//from ww  w  .  jav  a2s. c  o  m
        try {
            context = new AnnotationConfigApplicationContext(Class.forName(jobPath));
        } catch (ClassNotFoundException cnfe) {
            context = new ClassPathXmlApplicationContext(jobPath);
        }

        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        String jobName = jobIdentifier;

        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job = null;
        if (jobLocator != null) {
            try {
                job = jobLocator.getJob(jobName);
            } catch (NoSuchJobException e) {
            }
        }
        if (job == null) {
            job = (Job) context.getBean(jobName);
        }

        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        JobExecution jobExecution = launcher.run(job, jobParameters);
        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());

    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        CommandLineJobRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:org.springframework.cloud.function.adapter.aws.SpringFunctionInitializer.java

@SuppressWarnings("unchecked")
protected void initialize() {
    if (!this.initialized.compareAndSet(false, true)) {
        return;/* ww  w .j av a 2s.  c  o  m*/
    }
    logger.info("Initializing: " + configurationClass);
    SpringApplicationBuilder builder = new SpringApplicationBuilder(configurationClass);
    ConfigurableApplicationContext context = builder.web(false).run();
    context.getAutowireCapableBeanFactory().autowireBean(this);
    String name = context.getEnvironment().getProperty("function.name");
    boolean defaultName = false;
    if (name == null) {
        name = "function";
        defaultName = true;
    }
    if (this.catalog == null) {
        this.function = context.getBean(name, Function.class);
    } else {
        this.function = this.catalog.lookupFunction(name);
        this.name = name;
        if (this.function == null) {
            if (defaultName) {
                name = "consumer";
            }
            this.consumer = this.catalog.lookupConsumer(name);
            this.name = name;
            if (this.consumer == null) {
                if (defaultName) {
                    name = "supplier";
                }
                this.supplier = this.catalog.lookupSupplier(name);
                this.name = name;
            }
        }
    }
    this.context = context;
}

From source file:org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.java

protected void initialize(C targetContext) {
    if (!this.initialized.compareAndSet(false, true)) {
        return;//from  w  w w  .  j a v  a2  s . c  o  m
    }
    logger.info("Initializing: " + this.configurationClass);
    SpringApplication builder = springApplication();

    this.registerTargetContext(targetContext, builder);
    ConfigurableApplicationContext context = builder.run();
    context.getAutowireCapableBeanFactory().autowireBean(this);
    this.context = context;
    if (this.catalog == null) {
        initFunctionConsumerOrSupplierFromContext(targetContext);
    } else {
        initFunctionConsumerOrSupplierFromCatalog(targetContext);
    }
}

From source file:org.springframework.yarn.launch.AbstractCommandLineRunner.java

/**
 * Gets the Application Context.//from w w w .ja  va  2 s.  com
 *
 * @param configLocation the context config location
 * @return the configured context
 */
protected ConfigurableApplicationContext getApplicationContext(String configLocation) {

    ConfigurableApplicationContext context;
    if (ClassUtils.isPresent(configLocation, getClass().getClassLoader())) {
        Class<?> clazz = ClassUtils.resolveClassName(configLocation, getClass().getClassLoader());
        context = new AnnotationConfigApplicationContext(clazz);
    } else {
        context = new ClassPathXmlApplicationContext(configLocation);
    }

    context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
            AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
    return context;
}