001/*
002 * Copyright 2006-2013 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.springframework.batch.core.configuration.support;
017
018import org.springframework.batch.core.Job;
019import org.springframework.batch.core.configuration.JobFactory;
020import org.springframework.context.ApplicationContext;
021import org.springframework.context.ConfigurableApplicationContext;
022
023/**
024 * A {@link JobFactory} that creates its own {@link ApplicationContext} and
025 * pulls a bean out when asked to create a {@link Job}.
026 *
027 * @author Dave Syer
028 *
029 */
030public class ApplicationContextJobFactory implements JobFactory {
031
032        private final Job job;
033
034        /**
035         * @param jobName the id of the {@link Job} in the application context to be
036         * created
037         * @param applicationContextFactory a factory for an application context
038         * containing a job with the job name provided
039         */
040        public ApplicationContextJobFactory(String jobName, ApplicationContextFactory applicationContextFactory) {
041                @SuppressWarnings("resource")
042                ConfigurableApplicationContext context = applicationContextFactory.createApplicationContext();
043                this.job = context.getBean(jobName, Job.class);
044        }
045
046        /**
047         * Create an {@link ApplicationContext} from the factory provided and pull
048         * out a bean with the name given during initialization.
049         *
050         * @see org.springframework.batch.core.configuration.JobFactory#createJob()
051         */
052        @Override
053        public final Job createJob() {
054                return job;
055        }
056
057        /**
058         * Just return the name of instance passed in on initialization.
059         *
060         * @see JobFactory#getJobName()
061         */
062        @Override
063        public String getJobName() {
064                return job.getName();
065        }
066
067}