Example usage for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_TYPE

List of usage examples for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_TYPE

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_TYPE.

Prototype

int AUTOWIRE_BY_TYPE

To view the source code for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_TYPE.

Click Source Link

Document

Constant that indicates autowiring bean properties by type (applying to all bean property setters).

Usage

From source file:io.dohko.jdbi.spring.beans.factory.DBIRepositoryDefinitionBeanFactoryProcessor.java

/**
 * Defines an {@link IDBI} bean if and only if it is undefined.
 * <p> //from   w  w w  .j  ava  2s . c  om
 * 
 * @param beanFactory  the bean factory used by the application context
 */
private void defineIdbiBeanIfUndefined(ConfigurableListableBeanFactory beanFactory) {
    try {
        beanFactory.getBean(IDBI.class);
    } catch (NoSuchBeanDefinitionException undefinedIdbiBean) {
        try {
            beanFactory.getBean(DBI.class);
        } catch (NoSuchBeanDefinitionException undefinedDbiBean) {
            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                    .rootBeanDefinition(DBIFactoryBean2.class)
                    .addConstructorArgValue(beanFactory.getBean(DataSource.class))
                    .setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE)
                    .setScope(BeanDefinition.SCOPE_SINGLETON).getBeanDefinition();

            ((DefaultListableBeanFactory) beanFactory).registerBeanDefinition("dbi", beanDefinition);
        }
    }
}

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

/**
 * Batch Job? .//from w w w .  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("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:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java

/**
 * Batch Job? .//from www  .j av a2  s .co  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:org.springmodules.validation.valang.parser.DefaultVisitor.java

private Function lifeCycleCallbacks(Function function, int line, int column) {
    if (function instanceof BeanFactoryAware) {
        ((BeanFactoryAware) function).setBeanFactory(beanFactory);
    }//from w w  w . j a  v a  2  s.  co m
    if (function instanceof ApplicationContextAware) {
        ((ApplicationContextAware) function).setApplicationContext(applicationContext);
    }
    if (function instanceof ResourceLoaderAware) {
        ((ResourceLoaderAware) function).setResourceLoader(resourceLoader);
    }
    if (function instanceof MessageSourceAware) {
        ((MessageSourceAware) function).setMessageSource(messageSource);
    }
    if (function instanceof ApplicationEventPublisherAware) {
        ((ApplicationEventPublisherAware) function).setApplicationEventPublisher(applicationEventPublisher);
    }
    if (function instanceof ServletContextAware) {
        ((ServletContextAware) function).setServletContext(servletContext);
    }
    if (function instanceof AbstractFunction) {
        AbstractFunction abstractFunction = (AbstractFunction) function;
        AutowireCapableBeanFactory autowireCapableBeanFactory = null;

        if (abstractFunction.isAutowireByName() || abstractFunction.isAutowireByType()) {
            if (applicationContext instanceof ConfigurableApplicationContext) {
                ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
                autowireCapableBeanFactory = configurableApplicationContext.getBeanFactory();
            } else if (beanFactory instanceof AutowireCapableBeanFactory) {
                autowireCapableBeanFactory = (AutowireCapableBeanFactory) beanFactory;
            } else if (applicationContext == null && beanFactory == null) {
                throw new ValangException(
                        "Could not autowire function: no application context or bean factory available", line,
                        column);
            } else {
                throw new ValangException(
                        "Could not autowire function: application context or bean factory does not support autowiring",
                        line, column);
            }
        }
        if (abstractFunction.isAutowireByName()) {
            autowireCapableBeanFactory.autowireBeanProperties(function,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
        }
        if (abstractFunction.isAutowireByType()) {
            autowireCapableBeanFactory.autowireBeanProperties(function,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
        }
        try {
            abstractFunction.init();
        } catch (Exception e) {
            throw new ValangException("Error initializing function", e, line, column);
        }
    }
    return function;
}

From source file:de.zib.gndms.gndmc.test.gorfx.GORFXClientMain.java

private void getTaskFlowStatus(String id, String type, String wid) {
    Facets facets;//from ww w .j av  a2  s  . c o  m
    Facet f;
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:META-INF/client-context.xml");
    TaskFlowClient tfClient = (TaskFlowClient) context.getAutowireCapableBeanFactory()
            .createBean(TaskFlowClient.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
    tfClient.setServiceURL(gndmsEpUrl);

    System.out.println("Step 6: requesting facets of task flow, retrieving status results");
    ResponseEntity<Facets> res6 = tfClient.getFacets(type, id, dn);
    // should define facets status, result, errors
    facets = res6.getBody();
    f = facets.findFacet("status");
    if (f == null) {
        System.out.println("Status facet not found");
    } else {
        System.out.println(f.getName() + " " + f.getUrl());
        ResponseEntity<TaskFlowStatus> res7 = tfClient.getStatus(type, id, dn, wid);
        System.out.println(res7.getBody().toString());
    }

    f = facets.findFacet("result");
    if (f == null) {
        System.out.println("Result facet not found");
    } else {
        System.out.println(f.getName() + " " + f.getUrl());
        ResponseEntity<Specifier<TaskResult>> res8 = tfClient.getResult(type, id, dn, wid);
        System.out.println(res8.getBody().toString());
    }

    f = facets.findFacet("errors");
    if (f == null) {
        System.out.println("Errors facet not found");
    } else {
        System.out.println(f.getName() + " " + f.getUrl());
        ResponseEntity<TaskFlowFailure> res9 = tfClient.getErrors(type, id, dn, wid);
        if (res9.getStatusCode().equals(HttpStatus.OK)) {
            System.out.println("Failure" + res9.getBody().getFailureMessage());
        } else {
            System.out.println("No errors");

        }
    }
}

From source file:org.rosenvold.spring.convention.ConventionBeanFactory.java

@Override
protected synchronized RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
    if (super.containsBeanDefinition(beanName)) {
        return super.getMergedLocalBeanDefinition(beanName);
    }/*w  w w. j  av a 2s  . c o m*/
    final Class<?> type = getResolvedType(beanName);
    if (type != null) {
        RootBeanDefinition rootBeanDefinition = mergedBeanDefinitions.get(type);
        if (rootBeanDefinition == null) {
            rootBeanDefinition = new RootBeanDefinition(type);
            rootBeanDefinition.overrideFrom(getBeanDefinition(beanName));
            // Are these next two really necessary ???
            rootBeanDefinition.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE);
            rootBeanDefinition.setScope(getAnnotatedScope(type));
            mergedBeanDefinitions.put(type, rootBeanDefinition);
        }
        return rootBeanDefinition;
    }
    return null;
}

From source file:org.dspace.servicemanager.spring.SpringServiceManager.java

@SuppressWarnings("unchecked")
public <T> T registerServiceClass(String name, Class<T> type) {
    if (name == null || type == null) {
        throw new IllegalArgumentException("name and type must not be null for service registration");
    }//ww  w .j  a va2  s . c  o m
    T service;
    try {
        service = (T) applicationContext.getBeanFactory().autowire(type,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        registerBean(name, service);
    } catch (BeansException e) {
        throw new IllegalArgumentException(
                "Invalid service class (" + type + ") with name (" + name + ") registration: " + e.getMessage(),
                e);
    }
    return service;
}

From source file:org.apache.struts2.spring.StrutsSpringObjectFactory.java

/**
 * Constructs the spring object factory/*ww  w  . j  ava 2 s . c o  m*/
 * @param autoWire The type of autowiring to use
 * @param alwaysAutoWire Whether to always respect the autowiring or not
 * @param useClassCacheStr Whether to use the class cache or not
 * @param servletContext The servlet context
 * @since 2.1.3
 */
@Inject
public StrutsSpringObjectFactory(
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE, required = false) String autoWire,
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE_ALWAYS_RESPECT, required = false) String alwaysAutoWire,
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_USE_CLASS_CACHE, required = false) String useClassCacheStr,
        @Inject ServletContext servletContext, @Inject(StrutsConstants.STRUTS_DEVMODE) String devMode,
        @Inject Container container) {

    super();
    boolean useClassCache = "true".equals(useClassCacheStr);
    if (LOG.isInfoEnabled()) {
        LOG.info("Initializing Struts-Spring integration...");
    }

    Object rootWebApplicationContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    if (rootWebApplicationContext instanceof RuntimeException) {
        RuntimeException runtimeException = (RuntimeException) rootWebApplicationContext;
        LOG.fatal(runtimeException.getMessage());
        return;
    }

    ApplicationContext appContext = (ApplicationContext) rootWebApplicationContext;
    if (appContext == null) {
        // uh oh! looks like the lifecycle listener wasn't installed. Let's inform the user
        String message = "********** FATAL ERROR STARTING UP STRUTS-SPRING INTEGRATION **********\n"
                + "Looks like the Spring listener was not configured for your web app! \n"
                + "Nothing will work until WebApplicationContextUtils returns a valid ApplicationContext.\n"
                + "You might need to add the following to web.xml: \n" + "    <listener>\n"
                + "        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n"
                + "    </listener>";
        LOG.fatal(message);
        return;
    }

    String watchList = container.getInstance(String.class, "struts.class.reloading.watchList");
    String acceptClasses = container.getInstance(String.class, "struts.class.reloading.acceptClasses");
    String reloadConfig = container.getInstance(String.class, "struts.class.reloading.reloadConfig");

    if ("true".equals(devMode) && StringUtils.isNotBlank(watchList)
            && appContext instanceof ClassReloadingXMLWebApplicationContext) {
        //prevent class caching
        useClassCache = false;

        ClassReloadingXMLWebApplicationContext reloadingContext = (ClassReloadingXMLWebApplicationContext) appContext;
        reloadingContext.setupReloading(watchList.split(","), acceptClasses, servletContext,
                "true".equals(reloadConfig));
        if (LOG.isInfoEnabled()) {
            LOG.info("Class reloading is enabled. Make sure this is not used on a production environment!",
                    watchList);
        }

        setClassLoader(reloadingContext.getReloadingClassLoader());

        //we need to reload the context, so our isntance of the factory is picked up
        reloadingContext.refresh();
    }

    this.setApplicationContext(appContext);

    int type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; // default
    if ("name".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
    } else if ("type".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
    } else if ("auto".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
    } else if ("constructor".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
    } else if ("no".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_NO;
    }
    this.setAutowireStrategy(type);

    this.setUseClassCache(useClassCache);

    this.setAlwaysRespectAutowireStrategy("true".equalsIgnoreCase(alwaysAutoWire));

    if (LOG.isInfoEnabled()) {
        LOG.info("... initialized Struts-Spring integration successfully");
    }
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPagesServlet.java

@Override
protected void initFrameworkServlet() throws ServletException, BeansException {
    context = getServletContext();/*from   w  ww. j  ava2 s  . co  m*/
    context.log("GSP servlet initialized");
    context.setAttribute(SERVLET_INSTANCE, this);

    final WebApplicationContext webApplicationContext = getWebApplicationContext();
    grailsAttributes = new DefaultGrailsApplicationAttributes(context);
    webApplicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(this,
            AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
    groovyPagesTemplateEngine = webApplicationContext.getBean(GroovyPagesTemplateEngine.BEAN_ID,
            GroovyPagesTemplateEngine.class);

}

From source file:org.springframework.batch.core.jsr.launch.JsrJobOperator.java

/**
 * Public constructor used by {@link BatchRuntime#getJobOperator()}.  This will bootstrap a
 * singleton ApplicationContext if one has not already been created (and will utilize the existing
 * one if it has) to populate itself./* w w  w .  ja  v a 2 s. c  o  m*/
 */
public JsrJobOperator() {

    this.baseContext = BaseContextHolder.getInstance().getContext();

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

    if (taskExecutor == null) {
        taskExecutor = new SimpleAsyncTaskExecutor();
    }
}