스프링

 

 

1.  GlobalConfig

 

 

import java.util.Properties;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GlobalConfig {

	@Autowired
	private ApplicationContext context;
	
	@Autowired
	private ResourceLoader resourceLoader;
	
	
	private String uploadFilePath;
	
	/**
	 * @PostConstruct는 의존성 주입이 이루어진 후 초기화를 수행하는 메서드이다. 
	 * @PostConstruct가 붙은 메서드는 클래스가 service를 수행하기 전에 발생한다.
	 *  이 메서드는 다른 리소스에서 호출되지 않는다해도 수행된다. 
		
		@PostConstruct의 사용 이유
		1) 생성자가 호출되었을 때, 빈은 초기화되지 않았음(의존성 주입이 이루어지지 않았음) 
		이럴 때 @PostConstruct를 사용하면 의존성 주입이 끝나고 실행됨이 보장되므로 빈의 초기화에 대해서 걱정할 필요가 없다. 
		2) bean 의 생애주기에서 오직 한 번만 수행된다는 것을 보장한다. (어플리케이션이 실행될 때 한번만 실행됨)
		따라서 bean이 여러 번 초기화되는 걸 방지할 수 있다
		여기서는, ApplicationContext, ResourceLoader 가 의존성 주입이 완료되었는지에 대해 염려할 필요가 없다. 
	 */
	@PostConstruct
	public void init(){
		log.info("GlobalConfig-init" );
		String[] activeProfiles =context.getEnvironment().getActiveProfiles();
		String activeProfile="local"; // 기본위치 local
		if(ObjectUtils.isNotEmpty(activeProfiles)) {
			activeProfile=activeProfiles[0];
		}
		String resourcePath=String.format("classpath:globals/global-%s.properties", activeProfile);
		try {
			Resource resource=resourceLoader.getResource(resourcePath);
			Properties properties=PropertiesLoaderUtils.loadProperties(resource);
			uploadFilePath=properties.getProperty("uploadFile.path");
		}catch (Exception e) {
			log.error("e", e);
		}
		
	}
	
	
	
	public String getUploadFilePath() {
		return uploadFilePath;
	}
	
	
}

 

 

2. WebMvcConfig 에 bin 등록

 

	@Bean
	public GlobalConfig globalConfig(){
		return new GlobalConfig();
	}

 

 

3. properties 파일 추가

 

1) global-dev.properties

uploadFile.path= E:/upload/Ateam_upload

 

2) global-local.properties

uploadFile.path = /home/upload/

 

3) global-prod.properties

uploadFile.path= /var/www/html/upload

 

 

 

4) 사용 예

FileApiController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import kr.net.macaronics.configuration.GlobalConfig;
import kr.net.macaronics.configuration.http.BaseResponse;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/file")
@Api(tags="공통 프로젝트 프로퍼티 로컬, 개발, 운영 설정값 클래스로 관리 테스트 API")
@Slf4j
public class FileApiController {

	
	@Autowired
	private GlobalConfig globalConfig;
	
	
	@GetMapping("/upload")
	@ApiOperation(value="업로드", notes = "")
	public BaseResponse<Boolean> save(){
		log.debug("config : {} ", globalConfig);
		String uploadFilePath=globalConfig.getUploadFilePath();
		log.info("uploadFilePath  :  {} " , uploadFilePath);		
		return new BaseResponse<Boolean>(true);
	}
	
}

 

 

출력 결과 =>

Response body

Download

{
  "status": "SUCCESS",
  "code": "SUCCESS",
  "message": null,
  "pageMaker": null,
  "data": true
}

 

 

dev, local , prod  테스트 방법

 

 

 

 

소스

https://github.com/braverokmc79/sprig_boot_2.7.0_mybatis_board_project/commit/190c56e7279639ee6a35bcd28c908e6c818edc95

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  라이트

신주치레하다가 제(祭) 못 지낸다 , 겉치레만 하다가 정작 해야 할 일을 못 함을 비유하여 이르는 말.

댓글 ( 4)

댓글 남기기

작성