说明: 该方法实现了,通过继承JAR包中基类来获取properties中配置的相关属性,并添加至spring容器中,供代码中使用。
1。 基类
package com.ffcs.icity.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
/**
* 此类用于存放框架相关的配置.
*
*
*/
public abstract class BaseApplicationConfig implements InitializingBean {
@Value("${log.isDumpRequest:false}")
@FieldDescription("是否dump请求")
private boolean isDumpRequest = false;
@Value("${log.logger.root.level:DEBUG}")
@FieldDescription("日志级别等级")
private String logLevel = "DEBUG";
public boolean isDumpRequest() {
return isDumpRequest;
}
public String getLogLevel() {
return logLevel;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE);
}
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldDescription {
String value();
}
@Override
public void afterPropertiesSet() throws Exception {
// this.originalApplicationConfig = BeanUtils.copyObject(this, "originalApplicationConfig");
}
}
2。 配置文件内容
#log level
log.logger.root.level=DEBUG
#log open flag
log.isDumpRequest=true
3。 实现ApplicationContextAware接口,获取spring上下文相关类
package com.ffcs.icity.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* BaseApplicationConfig实例的获取
* @author linwei
*
*/
public class ApplicationConfigHolder implements ApplicationContextAware {
private final static Logger logger = LoggerFactory.getLogger(ApplicationConfigHolder.class);
private static BaseApplicationConfig applicationConfig;
public static <T> T getApplicationConfig() {
return (T)applicationConfig;
}
/**
* 通过实现ApplicationContextAware接口,获取Spring的实例上下文,并获取BaseApplicationConfig实例
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//获取类型为BaseApplicationConfig的BEAN
applicationConfig = applicationContext.getBean(BaseApplicationConfig.class);
logger.info("loaded initial application config:{}", applicationConfig);
}
}
package com.ffcs.icity.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Spring上下文的获取
* @author linwei
*
*/
public class ApplicationContextHolder implements ApplicationContextAware{
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return ApplicationContextHolder.applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextHolder.applicationContext=applicationContext;
}
}
package com.ffcs.icity.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 此类保存当前请求的上下文信息.
*
*
*/
public class RequestContextHolder {
/**
* 当前请求的请求对象
*/
private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();
/**
* 当前请求的请求对象
*/
private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();
/**
* 当前请求的请求参数
*/
private static ThreadLocal<Object> requestArgument = new ThreadLocal<Object>();
/**
* 当前请求的请求ID
*/
private static ThreadLocal<String> requestId = new ThreadLocal<String>();
public static HttpServletRequest getRequest() {
return request.get();
}
public static void setRequest(HttpServletRequest request) {
RequestContextHolder.request.set(request);
}
public static HttpServletResponse getResponse() {
return response.get();
}
public static void setResponse(HttpServletResponse response) {
RequestContextHolder.response.set(response);
}
public static Object getRequestArgument() {
return requestArgument.get();
}
public static void setRequestArgument(Object requestArgument) {
RequestContextHolder.requestArgument.set(requestArgument);
}
public static String getRequestId() {
return requestId.get();
}
public static void setRequestId(String requestId) {
RequestContextHolder.requestId.set(requestId);
}
public static void clear() {
request.remove();
response.remove();
requestArgument.remove();
requestId.remove();
}
}
说明:以上工具类可以存放至JAR包中,供其他的项目导入使用。
4。 在spring的web项目中,新建一个类,继承基类,并在spring中注入相关BEAN,即可获取其相关的属性信息,如下:
package com.ffcs.icity.support;
import com.ffcs.icity.config.BaseApplicationConfig;
public class ApplicationConfig extends BaseApplicationConfig {
}
spring的配置文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
default-lazy-init="false">
<!-- 自动扫描且只扫描@Controller -->
<context:component-scan base-package="com.ffcs.icity">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="springContext" class="com.ffcs.icity.support.TestApplicationContext" lazy-init="false"/>
<bean class="com.ffcs.icity.config.ApplicationContextHolder" />
<bean class="com.ffcs.icity.support.ApplicationConfig" />
<bean class="com.ffcs.icity.config.ApplicationConfigHolder" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<bean class="org.codehaus.jackson.map.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String"
value="yyyy-MM-dd HH:mm:ss">
</constructor-arg>
</bean>
</property>
</bean>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<!--<property name="interceptors">
<list>
<ref bean="stopWatchHandlerInterceptor"></ref>
<ref bean="handlerInterceptorTest1"></ref>
<ref bean="handlerInterceptorTest2"></ref>
</list>
</property>
--></bean>
<context:property-placeholder ignore-unresolvable="true" location="classpath*:/config.properties" />
</beans>
说明: 以上bean的设置请关闭延迟加载功能。即整个配置文件使用 default-lazy-init="false" 属性,或者在
<bean id="springContext" class="com.ffcs.icity.support.TestApplicationContext" lazy-init="false"/> bean中直接设置延迟加载关闭。
或者另外一种方式,打开延迟加载功能,但在代码中需要自己手动进行注入,即使用@Autowired 实现自己的手动注入,实现该bean的初始化工作。
因为延迟加载打开后,需要代码中手动注入才可以实现bean工厂的初始化。(延迟加载关闭,则在项目启动时,由web容器自动进行初始化加载。)
5. 代码直接调用例子:
可直接新建方法:isDumpRequest() ,这样就获取到最新的配置文件中配置的值。如配置文件未配置,则使用基类中定义的默认值.
private boolean isDumpRequest() {
return getApplicationConfig().isDumpRequest();
}
private BaseApplicationConfig getApplicationConfig() {
return ApplicationConfigHolder.getApplicationConfig();
}