Programming > Spring Framework

Properties 파일값 읽기( @Value로 읽어들이기 )

PropertySourcesPlaceholderConfigurer vs PropertiesFactoryBean

@Configuration
@EnableWebMvc
@EnableScheduling
@Import({DataBaseConfig.class})
@ComponentScan({"com.cyonesoft","com.emunhi.comm"})
@MapperScan("com.cyonesoft.web")
@PropertySource("classpath:config/${spring.profiles.active:office}/properties/application.properties")
public class WebConfig implements WebMvcConfigurer {
            
             @Bean
             public static PropertySourcesPlaceholderConfigurer propertyConfigPlaceon() {
                           return new PropertySourcesPlaceholderConfigurer();
             }
            
             @Bean
             public PropertiesFactoryBean applicationProperties() {
                           PropertiesFactoryBean bean = new PropertiesFactoryBean();
                           bean.setFileEncoding("UTF-8");
                           bean.setLocation(new ClassPathResource("config/"+System.getProperty("spring.profiles.active","office")+"/properties/application.properties"));
                           return bean;
             }

1) PropertySourcesPlaceholderConfigurer
  1. 메소드에 static 을 선언한다. (지정하지 않으면 @Value("${.....}")  사용시 null 발생
  2. properties 파일은 @PropertySource(.....) 를 통해 취득한다.
  3. java 에서 사용시  @Value("${database.url}" String dbUrl;  과 같이 사용한다.

@Controller
public class LoginController {
    static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Value("${database.url}")
    private String databaseUrl;
   
    @RequestMapping(value="/login")
    public String login( Model model, HttpServletRequest req) throws Exception {
        System.out.println(databaseUrl);
        return "login/login";
    }

2) PropertiesFactoryBean
  1. properties 파일은 메소드내 setLocation() 메소드를 사용해 취득한다.
  2. java 에서 사용시 @Value("#applicationProperties['database.url']}") String dbUrl;  과 같이 사용한다.
  3. java 에서 사용하는 id=#applicationProperties 는 Bean id=메소드명(default:미지정) 을 사용한다.

@Controller
public class LoginController {

    static final Logger logger = LoggerFactory.getLogger(LoginController.class);
   
    @Value("#{applicationProperties['database.url']}")
    private String databaseUrl;

    @RequestMapping(value="/login")
    public String login( Model model, HttpServletRequest req) throws Exception {
        System.out.println(databaseUrl);
        return "login/login";
    }

  1. JSP/javascript 에서 사용시 아래와 같이 사용

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>

[ in javascript ]
<spring:eval expression="@applicationProperties['database.url']" var="dbUrl"/>
var db = "${dbUrl}";

[ in jsp ]
<spring:eval expression="@applicationProperties['database.url']"/>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<script type="text/javascript">
$(function(){
    $.callbackLink = function(result){
        if(result.result=="OK"){
            <spring:eval expression="@applicationProperties['agent.url']" var="agentUrl"/>
            result.url = "${agentUrl}/login/agent";
        } else {
            alert(result.msg);
        }
    };
});
</script>
</head>
<body>

<div style="margin:10px;">

 

 

XML파일로 읽어들이기

  • XML로 설정된 PropertyPlaceholderConfigurer은 XML파일 내에서만 사용가능하다.

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="locations">
             <list>
                    <value>classpath:com/config/${spring.profiles.active}/jdbc.properties</value>
             </list>
       </property>
</bean>       

<bean id="dtSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="${jdbc.driverClassName}" />
       <property name="url" value="${jdbc.url}" />
       <property name="username" value="${jdbc.username}" />
       <property name="password" value="${jdbc.password}" />
</bean>

Java Config 에서 읽어들이기 - 방법1

  • Java Config에 의한 PropertyPlaceholderConfigurer을 사용할 경우 아래와 같이 Configuration에 Bean을 등록해서 사용가능하다.
  • XML과 Java Config 둘다 사용도 가능하다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 * @author emunhi
 *
 */
@Configuration
@PropertySource("classpath:com/config/${spring.profiles.active}/application.properties")
public class AppConfig {
       @Bean
       public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
             return new PropertySourcesPlaceholderConfigurer();
       }
}

  • 컨트롤러에서 사용하기 @Value

@Controller
@RequestMapping("/service")
public class PublicServiceController {

       @Value("${service.allow.ip}")
    String allowedIp;
      
       @Resource(name = "userService")
       private UserService userService;
 

Java Config 에서 읽어들이기 - 방법2

1) 프라퍼티파일 env.properties

# 폴더정보
PATH.ROOT=/data/image

2) 프라퍼티로딩

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 * @author emunhi
 *
 */
@Configuration
@PropertySource("classpath:resources/config/env.properties")
public class WebConfig {

       @Bean
       public static PropertySourcesPlaceholderConfigurer propertyConfig() {
             return new PropertySourcesPlaceholderConfigurer();
       }
}

3) 읽어들일 유틸 클래스

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;

/**
 * @author emunhi
 *
 */
@Repository
public class UtProperty {

       static Environment environment;
      
       @Autowired
       public void setEnvironment(Environment env) {
             environment = env;
       }
       public static String getProperty(String key) {
             return environment.getProperty(key);
       }
}

4) java 파일에서 사용하기

       // java 파일 아무데서나 취득가능
       public String getRootPath() {
             String pathRoot = UtProperty.getProperty("PATH.ROOT");
             return pathRoot;
       }