Eclipse IDE 2020‑03 을 다운받아 사용하려는데 Market에 PropertiesEditor이 없다..ㅡㅡ;;;;;

예전 것은 있으나 지원이 안된다고 한다..

그래서 결론은 수동으로 처리 해야 함.


다운로드 URL : http://propedit.sourceforge.jp/eclipse/updates 

여기서 PropertiesEditor 만 설치 하면 됨.

기본적으로 gradle 설치가 되어 있어야 한다.


바꾸는 명령어는 간단하다.


pom.xml이 있는 경로로 가서 


gradle init --type pom


이렇게 명령어를 실행하면 된다.


테스트 결과 완벽하게 모든 dependencies 옮겨지지 않는다.


일부 손이 가야 하지만 그래도 Maven보다 빠르고 쓰기 편하니 그걸로 족하다.

나 같은 경우 서브업무로 업무가 분리되어 있는 경우 업무를 처리하고 특정 Interface를 구현한 Class를 찾아서 후처리하는 기능 때문에 필요한 기능이었습니다.

추가적으로 찾은 Class에서 특정 Annotaion을 사용한 Method를 찾아서 실행하도록 하였습니다.


ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); 
provider.addIncludeFilter(new AssignableTypeFilter(Interface명.class));

Set components = provider.findCandidateComponents("Package명");  // co/kr/test형식

for (BeanDefinition component : components) {
    Class<?> clazz = Class.forName(component.getBeanClassName());
    logger.debug("Class Name : " + clazz.getName() );

    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        if( method.isAnnotationPresent(PostApprove.class) ) {
            logger.debug("Method Name : " + method.getName() );
            PostApprove annotation = method.getAnnotation(Annotation명.class);
            logger.debug("Annotation CODE : " + code + ", KEY : " + key );

            if( Arrays.asList(annotation.code()).contains(code) ) {
                String serviceValue = method.getDeclaringClass().getAnnotationsByType(Service.class)[0].value();
                ApproveHelper helper = (ApproveHelper) context.getBean(serviceValue);
         helper.postApprove(code, key);
           }
        }

    }
}


Java Configuration을 사용할 경우

public class WebMvcConfig extends WebMvcConfigurerAdapter {

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry

.addResourceHandler("/resources/**")

.addResourceLocations(

"/resources/",

"classpath:/META-INF/resources/resources"

);

}

}


xml 설정을 사용할 경우


<resources mapping="/resources/**" location="classpath:/META-INF/resources/resources/" />

- ajax로 보낼 경우

@RequestParam(value="arr[]" String[] arr)


- get 또는 post로 보낼 경우

@RequestParam(value="arr" String[] arr)

Data를 저장 시 저장되는 모든 정보를 이력으로 남겨 놓기 위하여 작성했습니다.


말들이 하도 많아서...ㅜㅜ



import java.lang.reflect.Method;

import java.util.Enumeration;


import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;


import org.apache.commons.lang3.ArrayUtils;

import org.apache.commons.lang3.StringUtils;

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.reflect.MethodSignature;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.stereotype.Component;

import org.springframework.util.ObjectUtils;

import org.springframework.web.context.request.RequestContextHolder;

import org.springframework.web.context.request.ServletRequestAttributes;


import com.duegosystem.esh.common.utils.RequestUtils;

import com.duegosystem.esh.config.aspect.operate.annotation.OperateLog;

import com.duegosystem.esh.config.aspect.operate.service.UserOpertHistService;

import com.duegosystem.esh.config.aspect.operate.vo.OperateHistVo;

import com.duegosystem.esh.config.security.vo.UserVo;


/**

 * @author Duego-Choi

 *

 */

@Aspect

@Component

public class OperateAdviceLogging {


private static final Logger logger = LoggerFactory.getLogger(OperateAdviceLogging.class);


@Resource(name = "userOpertHistService")

private UserOpertHistService userOpertHistService;


/**

* 등록 수정 삭제 시에만 적용합니다.

*

* @param joinPoint

* @return

* @throws Throwable

*/

@Around("execution(* com.duegosystem..*Controller.insert*(..)) || "

+ "execution(* com.duegosystem..*Controller.update*(..)) || "

+ "execution(* com.duegosystem..*Controller.delete*(..))")

public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {


logger.debug("Operate History Logging save processing.......................................");


Object principal = (Object) SecurityContextHolder.getContext().getAuthentication().getPrincipal();


HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())

.getRequest();


String httpMethod = request.getMethod();

MethodSignature signature = (MethodSignature) joinPoint.getSignature();

Method method = signature.getMethod();


logger.debug("httpMethod : " + httpMethod);

logger.debug("Class Method : " + method);


OperateHistVo operateHistVo = null;


/*

* 저장 수정 삭제 일경우만 사용하도록 하기 위해 POST 형식일 때만 적용되어지도록 처리

*/

if ("POST".equals(httpMethod)) {


if ((principal instanceof UserDetails)) {


operateHistVo = new OperateHistVo();


// 사용자 정보

UserVo user = (UserVo) principal;

logger.debug("empno : " + user.getEmpno());

logger.debug("emplNm : " + user.getEmplNm());


operateHistVo.setOpertId(user.getEmpno());

operateHistVo.setOpertNm(user.getEmplNm());


// 작업자 아이피

String ipAddress = RequestUtils.getRemoteIP(request);

logger.debug("ipAddress : " + ipAddress);

operateHistVo.setOpertIp(ipAddress);


// 접근 경로(메뉴 패턴)

String requestUri = request.getRequestURI();

String contextPath = request.getContextPath();

String pattern = requestUri.replaceAll("(^" + contextPath + ")|((\\.[^\\.]*)$)|((/[^/]+){1}/*$)", "")

+ "/";

logger.debug("Url pattern : " + pattern);

operateHistVo.setPattern(pattern);


String operateFile = requestUri.replace(contextPath, "").replace(pattern, "");

String operateType = "insert";

if (operateFile.startsWith("update")) {

operateType = "update";

} else if (operateFile.startsWith("delete")) {

operateType = "delete";

}

logger.debug("Operate Type : " + operateType);

operateHistVo.setOpertTy(operateType);


/*

* OperateLog Annotation을 통해서 등록하고자 하는 파라메터 또는 등록지 말아야 할 파라메터를

* 지정하였을 경우 처리합니다.

*

* 우선 순위는 등록해야할 파라메터가 있는 경우가 우선입니다.

*/

Enumeration<String> params = request.getParameterNames();


if (method.isAnnotationPresent(OperateLog.class)) {

OperateLog operateLog = method.getDeclaredAnnotation(OperateLog.class);


String[] saveParams = operateLog.params();

String[] notSaveParams = operateLog.notSaveParam();


// 저장하고자 하는 파라메타명을 설정하였을 경우

if (!ObjectUtils.isEmpty(saveParams)) {

while (params.hasMoreElements()) {

String paramName = (String) params.nextElement();

if (ArrayUtils.contains(saveParams, paramName)) {

if (!StringUtils.isEmpty(request.getParameter(paramName))) {

operateHistVo.addParam(paramName, request.getParameter(paramName));

}

}

}


// 저장하지 않을 파라메타명을 성정하였을 경우

} else if (!ObjectUtils.isEmpty(notSaveParams)) {

while (params.hasMoreElements()) {

String paramName = (String) params.nextElement();

if (ArrayUtils.contains(notSaveParams, paramName)) {

continue;

} else {

if (!StringUtils.isEmpty(request.getParameter(paramName))) {

operateHistVo.addParam(paramName, request.getParameter(paramName));

}

}

}

} else {

while (params.hasMoreElements()) {

String paramName = (String) params.nextElement();

if (!StringUtils.isEmpty(request.getParameter(paramName))) {

operateHistVo.addParam(paramName, request.getParameter(paramName));

}

}

}


} else {

while (params.hasMoreElements()) {

String paramName = (String) params.nextElement();

if (!StringUtils.isEmpty(request.getParameter(paramName))) {

operateHistVo.addParam(paramName, request.getParameter(paramName));

}

}

}


userOpertHistService.insert(operateHistVo);

}

}


Object obj = joinPoint.proceed();


/*

* Method에 해당하는 처리가 모두 끝난 후 후처리로 성공 상태 값을 Y로 바꿔준다.

*/

if ("POST".equals(httpMethod)) {

if (!ObjectUtils.isEmpty(operateHistVo)) {

try {

userOpertHistService.updateSuccess(operateHistVo.getOpertHistSeq());

} catch (Exception e) {

logger.error("OperateHist Advice Processing Error......!!!", e);

}

}

}


return obj;

}

}


Gradle의 멀티 프로젝트를 이용하여 모듈식 웹 프로젝트를 만들고 싶었다.

 

공통 부분과 그렇지 않은 부분을 업무별로 구성하여 각 프로젝트마다 필요한 업무를 조합하여 제공하고자 하는것이 목표였다.

 

열심히 구글링을 하였으나 멀티 프로젝트를 만드는 것은 많이 있지마 웹을 처리하는 방식은 없었다.

 

그래서 그냥 한번 이것 저것 찾아 보면서 한번 만들어 보기로 했다.

 

1. 전체 프로젝트 구조

 

 

프로젝트의 순서는 다음과 같이 정의 했다.

 

kamsi-system을 기본으로 하여 하위 프로젝트는 다음 순과 같이 정의를 하였다.


kamsi-common > kamsi-planner

 

kamsi-common을 kamsi-planner에서 Import 하여 배포하는 프로젝트라고 정의 했다.

 

 

 

2. Root Project

 

2.1. settings.gradle 생성

 

rootProject.name = 'kamsi-system'


include 'kamsi-common'
include 'kamsi-planner'

 

 

 

2.2. build.gradle

 

allprojects {


apply plugin: 'java'
apply plugin: 'eclipse-wtp'

ext {
     springVersion = '4.3.6.RELEASE'
     springSecurityVersion = '4.2.0.RELEASE'
     tilesVersion = '3.0.7'
     mybatisVersion = '3.4.1'
     mybatisSpringVersion = '1.3.0'
     log4jVersion = '2.8'
     poiVersion = '3.15'
}

 

repositories {
     mavenCentral()
     maven {
          name "OJDBC"
          url "http://repo.spring.io/libs-release"
     }
     maven {
          name "eGovFramework"
          url "http://maven.egovframe.kr:8080/maven/"
     }
 }

 

 dependencies {

  compile "org.springframework:spring-aop:${springVersion}"
  compile "org.springframework:spring-context:${springVersion}"
  compile "org.springframework:spring-web:${springVersion}"
  compile "org.springframework:spring-webmvc:${springVersion}"
  compile "org.springframework:spring-jdbc:${springVersion}"

  compile "org.springframework.security:spring-security-acl:${springSecurityVersion}"
  compile "org.springframework.security:spring-security-aspects:${springSecurityVersion}"
  compile "org.springframework.security:spring-security-config:${springSecurityVersion}"
  compile "org.springframework.security:spring-security-core:${springSecurityVersion}"
  compile "org.springframework.security:spring-security-taglibs:${springSecurityVersion}"
  compile "org.springframework.security:spring-security-web:${springSecurityVersion}"

  compile "org.springframework:spring-websocket:${springVersion}"

  compile "egovframework.rte:egovframework.rte.ptl.mvc:3.5.0"

  compile "org.mybatis:mybatis:${mybatisVersion}"
  compile "org.mybatis:mybatis-spring:${mybatisSpringVersion}"

  compile "org.aspectj:aspectjweaver:1.9.1"

  compile "javax.servlet:javax.servlet-api:3.1.0"
  compile "javax.servlet:jstl:1.2"
  compile "javax.servlet.jsp:jsp-api:2.2"

  compile "javax.validation:validation-api:1.1.0.Final"
  compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:2.5.2"

  compile "org.apache.tiles:tiles-api:${tilesVersion}"
  compile "org.apache.tiles:tiles-jsp:${tilesVersion}"

  compile "commons-io:commons-io:2.5"
  compile "commons-fileupload:commons-fileupload:1.3.2"
  compile "commons-beanutils:commons-beanutils:1.9.2"
  compile "org.apache.commons:commons-dbcp2:2.1"
  compile "org.apache.commons:commons-lang3:3.5"

  compile "org.apache.logging.log4j:log4j-slf4j-impl:${log4jVersion}"
  compile "org.apache.logging.log4j:log4j-core:${log4jVersion}"
  compile "org.apache.logging.log4j:log4j-api:${log4jVersion}"

  compile "org.hibernate:hibernate-validator:5.1.3.Final"

  compile "org.apache.poi:poi-ooxml-schemas:${poiVersion}"
  compile "org.apache.poi:poi:${poiVersion}"
  compile "org.apache.poi:poi-ooxml:${poiVersion}"
  compile "org.apache.poi:poi-scratchpad:${poiVersion}"

  compile "com.oracle:ojdbc6:12.1.0.1-atlassian-hosted"
  compile "org.bgee.log4jdbc-log4j2:log4jdbc-log4j2-jdbc4.1:1.16"

  compileOnly "org.projectlombok:lombok:1.16.20"
  compileOnly 'javax.servlet:javax.servlet-api:3.1.0'

}

}


subprojects {

task initSourceFolders {
     sourceSets*.java.srcDirs*.each {
         if( !it.exists() ) {
             it.mkdirs()
         }
     }

     sourceSets*.resources.srcDirs*.each {
         if( !it.exists() ) {
             it.mkdirs()
         }
     }


// webapp 폴더 생성

   def webappDir = new File("${projectDir}/src/main/webapp/WEB-INF")

   if( !webappDir.exists() ) {

webappDir.mkdirs()

   }

 }

}

 

위의 두가지 settings.gralde와 build.gradle을 생성 또는 수정한 후 Gradle build를 실행한다.

 

실행하고 나면 Eclipse 에 총 3개의 프로젝트가 생성되는것을 확인할 수 있다.

 

allprojects { ... } 생성되는 모든 프로젝트에 적용 되어져 모든 프로젝트에 Dependence에 정의된 라이브러리 들이 추가 된다.


subprojects { ... } 에 있는 내용은 하위 프로젝트에 source 파일이 담길 [ src/main/java, src/test/java] 와 [ src/main/webapp/WEB-INF ]를 생성하도록 설정 한다.

 

 

3. kamsi-common 프로젝트

 

앞서 말한바와 같이 프로젝트의 공통 부분이 들어갈 최상위 프로젝트이다.

 

Java Config 및 Security 또한 기본으로 사용되는 WEB Resource 등을 관리한다고 가정한다.

 

 

 

3.1 build.gradle

 

//apply plugin: 'war'

group = 'com.kamsi'
version = '0.0.1-SNAPSHOT'

 

jar {

metaInf {
    from 'src/main/webapp'
    into 'resources'

}

destinationDir rootProject.buildDir

}

 

위의 붉고 굵은 글씨의 항목이 중요한 부분이다.

 

지금까지 상위항목을 사용하기 위하여 이것저것을 해 보았지만 적용이 되지 않았다.

 

이클립스에서 java build path에 해당 프로젝트를 add 해도 적용이 되어지지 않았다.

 

그래서 구글링한 결과 사용하려면 jar 파일로 저장을 해서 import 시키는 것이 좋을 듯하다는 판단으로 소스를 jar로 묶어서 import 하였으나... 문제는 jsp 등 WEB-INF 하위에 있는 항목들을 불러 오지 못하는.... 그런 경우가 생겨 버렸다.

 

결국 jsp를 사용하고자 하면 jar 파일안에 있는 META-INF/resources 폴더 밑으로 들어가야 한다고 한다.

java 쪽에서 그렇게 정리를 해 놨다고 한다.

 

위의 붉고 굵은 글씨로 된 코드가 바로 그 부분이다.


이후 우리가 작성하던 방식대로 프로그램을 작성하면 된다.


4. kamsi-planner 프로젝트


해당 프로젝트에서는 kamsi-common을 사용하여 공통을 제외한 planner에 대하여만 작성을 하도록 설정한다.


4.1 build.gradle


apply plugin: 'war'


group = 'com.kamsi'

version = '0.0.1-SNAPSHOT'


war {

    baseName = 'duego-esh-web'

    version = '0.0.2-SNAPSHOT'

}


dependencies {

compile files("../build/kamsi-common-0.0.1-SNAPSHOT.jar")

}


jar {

    metaInf {

    from 'src/main/webapp'

    into 'resources'

    }


destinationDir rootProject.buildDir

}


/*********************************************************************

 * 테스트를 위한 jar 생성

 */

[compileJava, compileTestJava]*.options*.encoding = 'UTF-8' // 인코딩 UTF-8로 통일.


task subprojectBuild(type: Test) {

dependsOn ':kamsi-common:jar'

}


assemble.finalizedBy(subprojectBuild)

위의 소스와 같이 build과 정중 assemble task를 실행할 때 kamsi-common 프로젝트를 jar로 묶어주는 도록 처리를 했으며

또한 jar 파일을 묶은 kamsi-common 프로젝트를 dependencies 하도록 설정하였다.




이렇게 다 작성을 하고 kamsi-planner에서 WEB을 구동하였더니.....

Web Resources(css, javascript)를 찾아 오지 못하는 현상이 발생했다.


이러한 경우 jar 파일의 Web Resource 를 읽어 올수 있도록 처리를 해 줬다.


https://bit.ly/2lRwttG <-- 여기서 확인


이상으로 아주 간략하게 설정을 해 본 것이고... 

아주 초보적인 관점에서 처리 한것이라서... 


더 공부를 진행해야 겠다는 생각만이...ㅜㅜ


1. Eclipse 플러그인 설정


- Eclipse Marketplace 에서 gradle 검색


- Buildship Gradle Integration 2.0 인스톨




- 설치 완료 후 Ecilpse 재시작




2. Gradle 프로젝트 생성


- File > New > Project 메뉴 선택


- Gradle > Gradle Project 선택





3. Source Folder 및 Web Folder 생성


- Java Resources 에 Source Folder 추가

  

  : src/main/resources





- 하단 src/main 하위폴더로 Web Folder 생성


  : webapp

  : webapp/WEB-INF




전체 폴더 구조






3. Gradle 설정


- build.gradle 파일 오픈


- plugin 설정


apply plugin: 'java'

apply plugin: 'eclipse-wtp'

apply plugin: 'war'



- property 설정


ext {

  springVersion = '4.3.6.RELEASE'

  springSecurityVersion = '4.2.0.RELEASE'

  tilesVersion = '3.0.7'

  mybatisVersion = '3.4.1'

  mybatisSpringVersion = '1.3.0'

  log4jVersion = '2.8'

  poiVersion = '3.15'

}


- repositories 설정

repositories {
  mavenCentral()
  maven {
    name "eGovFramework"
    url "http://www.egovframe.go.kr/maven/"
  }
  maven {
    name "OJDBC"
    url "https://mvnrepository.com/artifact/com.jslsolucoes/ojdbc6/"
  }
}

dependencies 설정


dependencies {

  compile "org.springframework:spring-aop:$rootProject.ext.springVersion"

  compile "org.springframework:spring-context:$rootProject.ext.springVersion"
  ...

}

스프링 동적리스트 바인딩의 경우 최대 256개까지가 기본설정으로 되어 있다.


만약, 256개 이상을 파라미터로 넘기게 된다면 IndexOutOfBoundsException이 발생하게 될 것이다.



@InitBinder

public void initBinder(WebDataBinder binder) {

    binder.setAutoGrowCollectionLimit(1024);

}


위와 같이 Controller에 추가를 하여 해결하면 된다.


다른 방법으로 톰캣의 경우 설정하는 법도 있곤 한데.. 그냥 이걸로...ㅋ

Spring에서 코드성을 체크하는 validation 없어서 생성하기로 맘먹고 구글링 시작....^ ^

 

package com.company.common.validation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Documented
@Constraint(validatedBy=EnumConstraintValidator.class)
@Target( {ElementType.METHOD, ElementType.FIELD } )
@Retention(RetentionPolicy.RUNTIME)
public @interface Enum {

 String message() default "{message.validation.constraints.enum}";

 Class<?>[] groups() default{};

 Class<? extends Payload>[] payload() default {};

 String[] values() default {};

}

위와 같이 생성을 하고 나중에 이를 사용하게 됩니다. (@Enum)

그리고 아래 소스는 Validation 체크 하는 로직을 담당하는 소스입니다.

package com.company.common.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.ArrayUtils;

public class EnumConstraintValidator implements ConstraintValidator<Enum, String> {

 private String[] values;

 @Override
 public void initialize(Enum constraint) {
   values = constraint.values();
 }

 @Override
 public boolean isValid(String value, ConstraintValidatorContext context) {

  if( null == value ) return false;

  if( ArrayUtils.indexOf(values, value) > -1 ) return true;

  return false;
 }

}

 

사용은 아래와 같이~~~~

public class PayHist {

 @NotEmpty(groups={InsertProc.class})
 @Length(max=1)
 @Enum(values={"C","F"})
 private String gubun;           //서비스종류 : C-유료서비스 고객, F-무료서비스 고객

...

values :  허용되는 값 목록

values와 해당 값을 비교하여 일치 하지 않을 경우 오류를 발생합니다.

 

또한 default message 설정은 이클립스 resources 최상위에다가....

ValidationMessages.properties 이름으로 생성하여 주면 properties를 사용하여 메시지 출력이 가능합니다..ㅡㅡ;;

message.validation.constraints.enum={values} 만 등록이 가능합니다.

다른데 넣으면 안되더라구요...

 

Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'socialController' bean method 

원인 : Controller에 동일한 RequestMapping가 설정되어 있을경우 발생

@PropertySource로 Property 파일을 Evnironment로 로딩을 합니다.

아래는 예제 Sample입니다.

package com.intercast.schedule.dao;

 

import javax.annotation.Resource;

 

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;

 

@Repository("excelDao")
@PropertySource("classpath:properties/globals.properties")
public class ExcelDao {

 

 @Resource
 private MessageSource messageSource;

 

 @Resource
 private Environment environment;

 

 public void getExcelInfo() {
  System.out.println( "UPLOAD_FILE_PATH : " + environment.getProperty("UPLOAD_FILE_PATH") );
 }


}

 

굵은 글씨로 표시 한 부분이 해당 property를 inject 하고 사용하는 곳입니다.

프로퍼티가 여러개 일 경우에는 @PropertySources Annotation을 사용하시면 됩니다.

'JAVA > Spring(eGovFrame)' 카테고리의 다른 글

Custom Validation Annotion 생성  (0) 2015.08.26
[ERROR] Ambiguous mapping found.  (0) 2015.08.26
Spring4 Scheduling - Application  (0) 2015.05.19
Spring4 Scheduling - Demon  (0) 2015.05.19
Spring4 Scheduling - Spring 설정  (0) 2015.05.19

이제 마지막으로 자바를 구동하는 Application 파일입니다.

package com.intercast.schedule.stater;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.intercast.config.AppConfig;

 

public class Application {

 

 @SuppressWarnings("resource")
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  new AnnotationConfigApplicationContext(AppConfig.class);
 }

 

}

 

AnnotationConfigApplicationContext 을 이용하여 Spring 설정파일을 등록하고 실행하면 됩니다.

 

실행 : java -jar 자르파일명

'JAVA > Spring(eGovFrame)' 카테고리의 다른 글

[ERROR] Ambiguous mapping found.  (0) 2015.08.26
@PropertySource를 이용하여 Property 등록  (0) 2015.05.19
Spring4 Scheduling - Demon  (0) 2015.05.19
Spring4 Scheduling - Spring 설정  (0) 2015.05.19
Spring4 Scheduling - 환경설정  (0) 2015.05.19

실질적으로 Schedule를 설정하는 java 파일입니다.

 

package com.intercast.schedule.service;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;

 

public class Demon {

 

 @Resource(name="scheduleService") ScheduleService scheduleService;

 

 @Scheduled(cron="0/5 * * * * *")
 public void printHello() {
  scheduleService.insertUser();
 }

 

}

 

보시는 바와 같이 @Scheduled를 설정합니다.

Scheduled 설정에 관하여서는 따로 설명을 드리지 않겠습니다.

저의 경에는 cron을 사용하여 설정을 하였습니다.

이후의 방식은 MVC 방식의 Service 및 DAO 구현과 동일하게 진행하시면 됩니다.

Spring 설정은 두가지만 설정하면 됩니다.

Spring Scheduling 기본설정의 AppConfig.java와 Database 설정을 담당할 DatabaseConfig.java 입니다.

 

AppConfig.java 

package com.intercast.config;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import com.intercast.schedule.service.Demon;

 

@Configuration
@ComponentScan(value="com.intercast.schedule")
@EnableScheduling
@Import({DatabaseConfig.class})
public class AppConfig implements SchedulingConfigurer {

 

 @Bean
 public Demon demon() {
  return new Demon();
 }

 

 @Override
 public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
  // TODO Auto-generated method stub
  taskRegistrar.setScheduler(taskExecutor());
 }

 

 private Executor taskExecutor() {
  // TODO Auto-generated method stub
  return Executors.newScheduledThreadPool(10);
 }

 

}

 

위의 항목중에 @EnableScheduling 부분이 Annotation으로 설정된 @Scheduled 를 찾아 등록하고 실행 해 주는 부분입니다.

Demon을 Bean으로 등록을 하고 Demon에서 Schedule clon 설정을 해 주므로 구동이 시작됩니다.

 

DatabaseConfig 설정은 기존 Spring4 Java Config를 확인하시면 됩니다.

'JAVA > Spring(eGovFrame)' 카테고리의 다른 글

Spring4 Scheduling - Application  (0) 2015.05.19
Spring4 Scheduling - Demon  (0) 2015.05.19
Spring4 Scheduling - 환경설정  (0) 2015.05.19
Spring4 Scheduling - 폴더구조  (0) 2015.05.19
Spring4 JavaConfig 설정 - SecurityConfig.java  (3) 2015.04.23

+ Recent posts