Search

'Spring Framework'에 해당되는 글 2건

  1. 2010.09.14 Spring Quartz Batch (2)
  2. 2010.09.03 Tomcat 7 - Spring MVC 설치

Spring Quartz Batch

Programming/Java 2010.09.14 16:31 Posted by 파란크리스마스

출처 : http://wiki.dev.daewoobrenic.co.kr/mediawiki/index.php/Spring_Quartz_Batch

WEB-INF\web.xml

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   classpath:/job-bean.xml
  </param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

WEB-INF\classes\job-bean.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <import resource="classpath:simple-job-launcher-context.xml"/>
 <import resource="classpath:myHelloJob.xml"/>
 
 <bean id="helloJob" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="quartz.example.HelloJob" />
  <property name="jobDataAsMap">
   <map>
    <entry key="launcher" value-ref="jobLauncher"/>
    <entry key="job" value-ref="myHelloJob"/>
   </map>
  </property>
 </bean>

 <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
  <property name="jobDetail" ref="helloJob" />
  <property name="startDelay" value="10000" />
  <property name="repeatInterval" value="50000" />
 </bean>
 
 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="triggers">
   <list>
    <ref bean="simpleTrigger"/>
   </list>
  </property>
 </bean>
</beans>

WEB-INF\classes\simple-job-launcher-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <import resource="classpath:data-source-context.xml"/>

 <bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
  <property name="databaseType" value="MYSQL" />
  <property name="dataSource" ref="dataSource" />
  <property name="transactionManager" ref="transctionManager" />
 </bean>

 <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
  <property name="jobRepository" ref="jobRepository" />
 </bean>

 <bean id="simpleJob" class="org.springframework.batch.core.job.SimpleJob" abstract="true">
  <property name="jobRepository" ref="jobRepository" />
 </bean>

 <bean id="taskletStep" class="org.springframework.batch.core.step.tasklet.TaskletStep" abstract="true">
  <property name="jobRepository" ref="jobRepository" />
  <property name="transactionManager" ref="transctionManager" />
 </bean>

</beans>

WEB-INF\classes\data-source-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <import resource="classpath:data-source-context-init.xml"/>

 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="org.gjt.mm.mysql.Driver"></property>
  <property name="url" value="jdbc:mysql://127.0.0.1:5141/batch"></property>
  <property name="username" value="sa"></property>
  <property name="password" value="sqldba"></property>
 </bean>

 <bean id="transctionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
  lazy-init="true">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

</beans>

WEB-INF\classes\data-source-context-init.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <bean id="initializingFactoryBean" class="quartz.example.InitializingDataSourceFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="initScript">
   <value>classpath:schema-mysql.sql</value>
  </property>
 </bean>
 
</beans>

WEB-INF\classes\myHelloJob.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <bean id="myHelloJob" parent="simpleJob">
  <property name="name" value="myHelloJob" />
  <property name="steps">
   <list>
    <bean id="firstHello" parent="taskletStep">
     <property name="tasklet">
      <bean class="quartz.example.MyHello">
       <property name="message" value="Hi~" />
      </bean>
     </property>
    </bean>
   </list>
  </property>
 </bean>
 
</beans>

package quartz.example;

public class InitializingDataSourceFactoryBean extends AbstractFactoryBean {

 private Resource initScript;
 private Resource destroyScript;
 DataSource dataSource;

 protected Object createInstance() throws Exception {
  
  Assert.notNull(dataSource);
  try {
   doExecuteScript(destroyScript);
  }
  catch (Exception e) {
   logger.debug("Could not execute destroy script [" + destroyScript + "]", e);
  }
  doExecuteScript(initScript);
  return dataSource;
 }

 private void doExecuteScript(final Resource scriptResource) {
  
  try {
  
   if (scriptResource == null || !scriptResource.exists())
    return;
   TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
   if (initScript != null) {
    transactionTemplate.execute(new TransactionCallback() {

     public Object doInTransaction(TransactionStatus status) {
      JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
      String[] scripts;
      try {
       scripts = StringUtils.delimitedListToStringArray(stripComments(IOUtils.readLines(scriptResource
         .getInputStream())), ";");
      }
      catch (IOException e) {
       throw new BeanInitializationException("Cannot load script from [" + initScript + "]", e);
      }
      for (int i = 0; i < scripts.length; i++) {
       String script = scripts[i].trim();
       if (StringUtils.hasText(script)) {
        jdbcTemplate.execute(scripts[i]);
       }
      }
      return null;
     }

    });

   }
  } catch (Exception e) {
   logger.debug("기존에 스키마가 생성된 경우 오류가 발생 할 수 있으며, 오류 발생시 무시", e);
  }
 }

 private String stripComments(List list) {
  StringBuffer buffer = new StringBuffer();
  for (Iterator iter = list.iterator(); iter.hasNext();) {
   String line = (String) iter.next();
   if (!line.startsWith("//") && !line.startsWith("--")) {
    buffer.append(line + "\n");
   }
  }
  return buffer.toString();
 }

package quartz.example;

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;

public class MyHello implements InitializingBean, Tasklet {
 
 private static Log _log = LogFactory.getLog(MyHello.class);
 
 private String message = "";
 
 public void setMessage(String message) {
  this.message = message;
 }

 @Override
 public void afterPropertiesSet() throws Exception {
  _log.info("========= " + this.getClass().getSimpleName() + "=============" + message);
 }

 @Override
 public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
  _log.info(">>>>>>>>>>> " + this.getClass().getSimpleName() + "=====" + message );
  
  return RepeatStatus.FINISHED;
 }

}

package quartz.example;

import java.util.Date;
import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.scheduling.quartz.QuartzJobBean;

//public class HelloJob implements Job {
public class HelloJob extends QuartzJobBean {

  private static Log _log = LogFactory.getLog(HelloJob.class);
    
  private JobLauncher launcher;
  private Job job;
    
  private int count = 0;
    
  public void setLauncher(JobLauncher launcher) {
    this.launcher = launcher;
  }

  public void setJob(Job job) {
    this.job = job;
  }

  public HelloJob() {
  }
    
  protected void executeInternal(JobExecutionContext context) {
    _log.info("<<<<<<<< " +  " Hello World! - " + new Date() + " >>>>>>>>");
     
    System.out.println("aaaa");
     
    JobParametersBuilder jobParameterBulider = new JobParametersBuilder();
    jobParameterBulider.addDate("date", new Date());
     
    try {
      JobExecution jobExecution = launcher.run(job, jobParameterBulider.toJobParameters());
   
      for(Iterator<StepExecution> iterator = 
        jobExecution.getStepExecutions().iterator(); iterator.hasNext();) {
          StepExecution stepExecution = iterator.next();
        }
    } catch (JobExecutionAlreadyRunningException e) {
      e.printStackTrace();
    } catch (JobRestartException e) {
      e.printStackTrace();
    } catch (JobInstanceAlreadyCompleteException e) {
      e.printStackTrace();
    }
  }
}

신고

Tomcat 7 - Spring MVC 설치

Programming/Java 2010.09.03 17:08 Posted by 파란크리스마스

출처 : http://pelican7.egloos.com/2584679

Tomcat 7
Spring Framework 3.0.3.RELEASE
Eclipse 3.6

간단하게 브라우저에서 hello.htm을 호출하면 내부에서 hello.jsp를 호출하는 예제입니다.

1. Project 생성



2. jar 복사

경로 : SpringMVC\WebContent\WEB-INF\lib

commons-logging-1.1.1.jar
org.springframework.asm-3.0.4.RELEASE.jar
org.springframework.beans-3.0.4.RELEASE.jar
org.springframework.context-3.0.4.RELEASE.jar
org.springframework.core-3.0.4.RELEASE.jar
org.springframework.expression-3.0.4.RELEASE.jar
org.springframework.web-3.0.4.RELEASE.jar
org.springframework.web.servlet-3.0.4.RELEASE.jar

3. web.xml 파일 작성

경로 : SpringMVC\WebContent\WEB-INF

---------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0">

  <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>
      index.jsp
    </welcome-file>
  </welcome-file-list>

</web-app>
---------------------------------------

4. springapp-servlet.xml 파일 작성

경로 : SpringMVC\WebContent\WEB-INF

---------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <!-- the application context definition for the springapp DispatcherServlet -->

  <bean name="/hello.htm" class="springapp.web.HelloController"/>

</beans>
---------------------------------------

5. HelloController.java 작성 / 컴파일

---------------------------------------
package springapp.web;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

public class HelloController implements Controller {

    protected final Log logger = LogFactory.getLog(getClass());

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        logger.info("Returning hello view");

        return new ModelAndView("hello.jsp");
    }
}
---------------------------------------

6. hello.jsp 파일 작성

경로 : SpringMVC\WebContent

---------------------------------------
 <html>
  <head><title>Hello :: Spring Application</title></head>
  <body>
    <h1>Hello - Spring Application</h1>
    <p>Greetings.</p>
  </body>
</html>
---------------------------------------

7. Test

http://localhost:8080/SpringMVC/hello.htm


신고


 

티스토리 툴바