resetful项目搭建(四):项目开始的基本开发配置
2017-12-20 本文已影响0人
oo_pp
所有的项目搭建完了,接下来要做一些基本的配置开发
- core项目的spring配置 : applicationContext-core.xml
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<!-- 引入全局的jdbc配置文件 -->
<context:property-placeholder location="classpath:/jdbc/ourfor.properties"
ignore-unresolvable="true" />
<!-- jasypt保护数据库配置 -->
<bean id="environmentVariablesConfiguration" class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">
<property name="password" value="test" />
</bean>
<bean id="configurationEncryptor" class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
<property name="config" ref="environmentVariablesConfiguration" />
</bean>
<!-- 读取jdbc的配置文件 -->
<bean id="propertyConfigurer" class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer">
<constructor-arg ref="configurationEncryptor" />
<property name="locations">
<list>
<value>classpath:/jdbc/jdbc.*.properties</value>
</list>
</property>
<property name="fileEncoding" value="utf-8" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
<!-- 开启AOP监听 只对当前配置文件有效 -->
<aop:aspectj-autoproxy expose-proxy="true"/>
<context:annotation-config />
<!-- 指定需要spring托管的包 -->
<context:component-scan base-package="test.core" />
</beans>
- base项目的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:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
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:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="test.base">
<!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> -->
</context:component-scan>
<!-- base -->
<bean id="dataSourceBaseServer" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${baseserver.jdbc.url}" />
<property name="username" value="${baseserver.jdbc.username}" />
<property name="password" value="${baseserver.jdbc.password}" />
<property name="filters" value="stat" />
<property name="maxActive" value="50" />
<property name="initialSize" value="10" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- <property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="50" /> -->
</bean>
<bean id="sessionFactoryBase"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSourceBaseServer" />
</property>
<!-- 需要spring托管的bean -->
<property name="packagesToScan">
<list>
<value>test.base.*.bean</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${baseserver.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
<prop key="javax.persistence.validation.mode">none</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
<prop key="hibernate.order_updates">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory </prop>
</props>
</property>
</bean>
<bean id="transactionManagerBase"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactoryBase" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerBase" />
</beans>
- core项目中重写下sql方言,处理mysql编码问题
package test.core.dialet;
import org.hibernate.dialect.MySQL5InnoDBDialect;
public class MySQL5DialectUTF8 extends MySQL5InnoDBDialect {
@Override
public String getTableTypeString() {
return " ENGINE=InnoDB DEFAULT CHARSET=utf8";
}
}
-
在web项目中添加配置文件
image.png
jdbc.test.properties:数据库的链接配置(*改为自己的数据库信息)
baseserver.jdbc.driverClassName=com.mysql.jdbc.Driver
baseserver.jdbc.url=jdbc\:mysql\://***\:3306/test_base?zeroDateTimeBehavior\=convertToNull&useUnicode\=true&characterEncoding\=utf-8&autoReconnect\=true&failOverReadOnly\=false
baseserver.jdbc.username=***
baseserver.jdbc.password=***
baseserver.hibernate.dialect=test.core.dialet.MySQL5DialectUTF8
test.properties : hibernate和druid的一些配置
#显示sql语句
hibernate.show_sql=true
#格式化sql语句
hibernate.format_sql=true
#在SQL中生成有助于调试的注释信息
hibernate.use_sql_comments=true
hibernate.generate_statistics=true
hibernate.hbm2ddl.auto=update
#阿里druid的配置信息
druid.maxActive=50
druid.initialSize=10
druid.maxWait=60000
druid.minIdle=1
appConfig.properties:项目启动的配置文件,主要存储一些动态配置信息
@profiles=deploy
#deploy
[appConfig]
cookieIndate=7200
apps=
log4j.properties:日志配置文件,可以不需要,视自己情况而定
### 设置###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.Threshold = INFO
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} %l method:%n%m%n%n
### 输出DEBUG 级别以上的日志到=E://logs/debug.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/debug.log
log4j.appender.D.DatePattern = '.'yyyy-MM-dd
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E\://logs/error.log
log4j.appender.E.DatePattern = '.'yyyy-MM-dd
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n
- 编写PropsUtil和GlobalConfig类,读取配置文件
PropsUtil.java
package test.core.utils;
import com.google.common.base.Strings;
import java.io.IOException;
import java.io.InputStream;
import jodd.props.Props;
public class PropsUtil
{
private Props props = null;
public PropsUtil(String filename)
throws IOException
{
InputStream in = PropsUtil.class.getClassLoader().getResourceAsStream(filename);
this.props = new Props();
this.props.load(in);
in.close();
}
public PropsUtil(Class<?> s, String filename)
throws IOException
{
InputStream in = s.getResourceAsStream(filename);
this.props = new Props();
this.props.load(in);
in.close();
}
public Props getPorps()
{
return this.props;
}
public String getValue(String key, String defValue)
{
String result = this.props.getValue(key);
if (Strings.isNullOrEmpty(result)) {
return defValue;
}
return result;
}
}
GlobalConfig.java
package test.core.config;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import org.apache.log4j.Logger;
import test.core.utils.PropsUtil;
public class GlobalConfig
{
private static final Logger log = Logger.getLogger(GlobalConfig.class);
public static boolean druidMonitor = true;
public static boolean useClientFilter = false;
public static String apps = null;
//cookie有效期
public static int cookieIndate = 86400;
//是否开启跨域
public static boolean cross = false;
//authToken有效期
public static int authValid = 86400;
static
{
try
{
System.out.println("正在加载配置文件...");
PropsUtil p1 = new PropsUtil("appConfig.properties");
String[] profile = p1.getPorps().getActiveProfiles();
System.out.println("profiles is " + JSON.toJSONString(profile));
useClientFilter = Boolean.valueOf(p1.getValue("appConfig.useClientFilter", String.valueOf(useClientFilter))).booleanValue();
cookieIndate = Integer.parseInt(p1.getValue("appConfig.cookieIndate", String.valueOf(cookieIndate)));
cross = Boolean.valueOf(p1.getValue("appConfig.cross", String.valueOf(cross))).booleanValue();
authValid = Integer.parseInt(p1.getValue("appConfig.authValid", String.valueOf(authValid)));
apps = p1.getPorps().getValue("appConfig.apps");
}
catch (IOException e)
{
log.warn("读取 appConfig.props 出错!", e);
}
}
}
- jersey的相关配置类:RestApplication.java
package test.core.config;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.server.ResourceConfig;
public class RestApplication extends ResourceConfig {
public RestApplication() {
packages("test");
//打印访问日志,便于跟踪调试,正式发布可清除
register(LoggingFeature.class);
//注册JSON转换器
register(JacksonJsonProvider.class);
}
}
- 跨域相关的过滤器,解决跨域问题,重写了org.apache.catalina.filters.CorsFilter类,重写的原因貌似是因为原本的类不支持delete和put请求,类有些大,就不贴出来了,只贴出修改的部分
public static final String DEFAULT_ALLOWED_HTTP_METHODS = "GET,POST,HEAD,OPTIONS,PUT,DELETE";
- 项目中采用实现WebApplicationInitializer的方式来代替web.xml的配置访问,编写TestWebApplicationInitializer类,定义启动配置
package test.core.config;
import com.google.common.base.Strings;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.util.IntrospectorCleanupListener;
//定义执行顺序
@Order(1)
public class TestWebApplicationInitializer implements WebApplicationInitializer {
private void setInitParameter(ServletContext servletContext) {
ArrayList<String> list = new ArrayList<String>();
//默认加载base和core项目的spring配置文件,并根据appConfig.properties中的app项动态加载其它子项目的spring配置文件
list.add("classpath:applicationContext-core.xml");
list.add("classpath:applicationContext-base-server.xml");
String apps = GlobalConfig.apps;
if (!Strings.isNullOrEmpty(apps)) {
System.out.println("loading config files:");
String[] applist = apps.split(";");
for (String app : applist) {
list.add(app);
System.out.println("\t" + app);
}
}
String config = StringUtils.join(list.toArray(), ",");
servletContext.setInitParameter("contextConfigLocation", config);
}
public void onStartup(ServletContext servletContext)
throws ServletException {
setInitParameter(servletContext);
//此监听器主要用于解决java.beans.Introspector导致的内存泄漏的问题
servletContext.addListener(IntrospectorCleanupListener.class);
//Spring监听器
servletContext.addListener(ContextLoaderListener.class);
//ServletRequestListener监听器接口
servletContext.addListener(RequestContextListener.class);
//Spring字符集过滤器,用于处理项目中的乱码问题
FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding","org.springframework.web.filter.CharacterEncodingFilter");
characterEncoding.setInitParameter("forceEncoding", "true");
characterEncoding.setInitParameter("encoding", "UTF-8");
characterEncoding.addMappingForUrlPatterns(null, true,new String[] { "/rest/*" });
//jersey的相关配置
ServletRegistration.Dynamic jerseyServlet = servletContext.addServlet("JerseyServlet","org.glassfish.jersey.servlet.ServletContainer");
HashMap<String, String> jerseyServletMap = new HashMap<String, String>();
jerseyServletMap.put("javax.ws.rs.Application","test.core.config.RestApplication");
//返回数据过滤器,使用GZIP过滤器压缩
jerseyServletMap.put("com.sun.jersey.spi.container.ContainerRequestFilters","com.sun.jersey.api.container.filter.GzipFilter");
jerseyServlet.setInitParameters(jerseyServletMap);
jerseyServlet.setLoadOnStartup(1);
jerseyServlet.addMapping(new String[] { "/rest/*" });
//跨域过滤器
if(GlobalConfig.cross){
FilterRegistration.Dynamic CorsFilter = servletContext.addFilter("CorsFilter","test.core.filters.CorsFilter");
CorsFilter.addMappingForUrlPatterns(null, true,new String[] { "/rest/*" });
CorsFilter.setInitParameter("cors.allowed.headers", "range,content-type");
CorsFilter.setInitParameter("cors.exposed.headers", "Content-Range");
}
//druid monitor 监控
if (GlobalConfig.druidMonitor) {
FilterRegistration.Dynamic druidWebStatFilter = servletContext.addFilter("DruidWebStatFilter","com.alibaba.druid.support.http.WebStatFilter");
druidWebStatFilter.setInitParameter("exclusions","*.html,*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
druidWebStatFilter.addMappingForUrlPatterns(null, true,new String[] { "/*" });
ServletRegistration.Dynamic druidStatViewServlet = servletContext.addServlet("DruidStatView","com.alibaba.druid.support.http.StatViewServlet");
druidStatViewServlet.addMapping(new String[] { "/druid/*" });
druidStatViewServlet.setInitParameter("loginUsername","ourfor");
druidStatViewServlet.setInitParameter("loginPassword","rofruo");
}
}
}