利用Spring的ServletContextAware給ServletContext初始化資料
阿新 • • 發佈:2019-02-13
package com.xxx
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
@Component
@Lazy(false)
public class PropertyHolder implements ServletContextAware {
private static ServletContext servletContext;
private static String uploadDir;
// 生成的js檔案存放目錄
private static String jsGenerateDir;
/**
* 給上下文設定值
*/
@Override
public void setServletContext(ServletContext servletContext) {
PropertyHolder.servletContext = servletContext;
servletContext.setAttribute("ctx" , servletContext.getContextPath());
servletContext.setAttribute("uploadDir", uploadDir);
//TODO 初始化任何值
}
//從配置檔案(/application.properties)給屬性賦值,其中upload.dir 配置檔案在專案根路徑,裡面定義了upload.dir才能賦值成功,否則初始化事值為null
@Value("${upload.dir}")
public void setUploadDir(String uploadDir) {
PropertyHolder.uploadDir = uploadDir;
}
//TODO 從配置檔案初始化任何屬性
//It's so easy! let's get it;
}