spring mvc 零配置实例

本文紧接着上一篇文章Spring mvc + Hibernate + Jpa + druid 全注解配置实例,推荐先掌握上一篇文章。

介绍

零配置是servlet3.0之后支持的方式,所有servlet的版本以及运行容器的servlet版本需要3.0+版本。
本文与前文不同的是没有配置文件,包括web.xml也是无内容的。替换方式是采用Java代码实现。pom.xml文件与上文一致,web.xml为空,spring相关配置全无。
包括初始化、数据源、mvc、容器等

初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;

/**
* Created by Administrator on 2015/12/25.
*/

public class Initializer implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
servletContext.addListener(new ContextLoaderListener(ctx));

ctx.setServletContext(servletContext);

ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);

CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
encodingFilter.setForceEncoding(true);
FilterRegistration.Dynamic encodingServlet = servletContext.addFilter("encodingFilter", encodingFilter);
encodingServlet.addMappingForUrlPatterns(null,true,"/*");

WebStatFilter webStatFilter = new WebStatFilter();
FilterRegistration.Dynamic webStatServlet = servletContext.addFilter("DruidWebStatFilter", webStatFilter);
webStatServlet.setInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
webStatServlet.addMappingForUrlPatterns(null,true,"/*");

ServletRegistration.Dynamic druidStatViewServlet = servletContext.addServlet("DruidStatView",new StatViewServlet());
druidStatViewServlet.addMapping("/druid/*");
}
}

可以和web.xml对照看。

spring 相关

包括两个文件,当然还可以更细分,用@import导入即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

/**
* Created by Administrator on 2015/12/25.
*/

@Configuration
@ComponentScan("com.zzcm.tmp")
@EnableWebMvc
@EnableTransactionManagement(proxyTargetClass = true)
@PropertySource("classpath:db.properties")
@Import({MvcConfig.class})
public class WebAppConfig {

private static final Logger LOG = LoggerFactory.getLogger(WebAppConfig.class);

private static final String P_DB_DRIVER = "db.driver";
private static final String P_DB_PASSWORD = "db.password";
private static final String P_DB_URL = "db.url";
private static final String P_DB_USERNAME = "db.username";

private static final String P_DB_MAXACTIVE = "db.maxActive";
private static final String P_DB_INITSIZE = "db.initialSize";
private static final String P_DB_MAXWAIT = "db.maxWait";
private static final String P_DB_MINIDLE = "db.minIdle";
private static final String P_DB_TBERM = "db.timeBetweenEvictionRunsMillis";
private static final String P_DB_MEITM = "db.minEvictableIdleTimeMillis";
private static final String P_DB_VQ = "db.validationQuery";
private static final String P_DB_TESTWHILEIDEL = "db.testWhileIdle";
private static final String P_DB_TESTONBORROW = "db.testOnBorrow";
private static final String P_DB_TESTONRETURN = "db.testOnReturn";
private static final String P_DB_FILTERS = "db.filters";


private static final String P_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String P_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String P_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
private static final String P_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String P_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String P_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String P_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
private static final String P_HIBERNATE_CACHE_P_CLASS = "hibernate.cache.provider_class";
private static final String P_PERSISTENCE_VALI_MODE = "javax.persistence.validation.mode";
private static final String P_HIBERNATE_EJB_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";

@Resource
private Environment env;


@Bean
public UrlBasedViewResolver setupViewResolver(){
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}

@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(P_DB_DRIVER));
dataSource.setUrl(env.getRequiredProperty(P_DB_URL));
dataSource.setUsername(env.getRequiredProperty(P_DB_USERNAME));
dataSource.setPassword(env.getRequiredProperty(P_DB_PASSWORD));

dataSource.setMaxActive(env.getRequiredProperty(P_DB_MAXACTIVE, Integer.class));
dataSource.setInitialSize(env.getRequiredProperty(P_DB_INITSIZE, Integer.class));
dataSource.setMaxWait(env.getRequiredProperty(P_DB_MAXWAIT, Integer.class));
dataSource.setMinIdle(env.getRequiredProperty(P_DB_MINIDLE, Integer.class));
dataSource.setTimeBetweenEvictionRunsMillis(env.getRequiredProperty(P_DB_TBERM, Integer.class));
dataSource.setMinEvictableIdleTimeMillis(env.getRequiredProperty(P_DB_MEITM, Long.class));
dataSource.setValidationQuery(env.getRequiredProperty(P_DB_VQ));
dataSource.setTestWhileIdle(env.getRequiredProperty(P_DB_TESTWHILEIDEL, Boolean.class));
dataSource.setTestOnBorrow(env.getRequiredProperty(P_DB_TESTONBORROW, Boolean.class));
dataSource.setTestOnReturn(env.getRequiredProperty(P_DB_TESTONRETURN, Boolean.class));
try {
dataSource.setFilters(env.getRequiredProperty(P_DB_FILTERS));
} catch (SQLException e) {
LOG.error("Create DataSource filters failed.",e);
}
return dataSource;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(dataSource());
bean.setPackagesToScan(env.getRequiredProperty(P_ENTITYMANAGER_PACKAGES_TO_SCAN));
//b.setPersistenceUnitName("mysqldb");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(env.getRequiredProperty(P_HIBERNATE_SHOW_SQL,Boolean.class));
adapter.setDatabasePlatform(env.getRequiredProperty(P_HIBERNATE_DIALECT));
bean.setJpaVendorAdapter(adapter);
bean.setJpaProperties(jpaProperties());
return bean;
}

private Properties jpaProperties(){
Properties prop = new Properties();
prop.put(P_HIBERNATE_MAX_FETCH_DEPTH, env.getRequiredProperty(P_HIBERNATE_MAX_FETCH_DEPTH, Integer.class));
prop.put(P_HIBERNATE_JDBC_FETCH_SIZE, env.getRequiredProperty(P_HIBERNATE_JDBC_FETCH_SIZE, Integer.class));
prop.put(P_HIBERNATE_JDBC_BATCH_SIZE, env.getRequiredProperty(P_HIBERNATE_JDBC_BATCH_SIZE, Integer.class));
prop.put(P_HIBERNATE_SHOW_SQL, env.getRequiredProperty(P_HIBERNATE_SHOW_SQL, Boolean.class));
prop.put(P_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(P_HIBERNATE_FORMAT_SQL, Boolean.class));
prop.put(P_HIBERNATE_CACHE_P_CLASS, env.getRequiredProperty(P_HIBERNATE_CACHE_P_CLASS));
prop.put(P_PERSISTENCE_VALI_MODE, env.getRequiredProperty(P_PERSISTENCE_VALI_MODE));
prop.put(P_HIBERNATE_EJB_NAMING_STRATEGY, env.getRequiredProperty(P_HIBERNATE_EJB_NAMING_STRATEGY));

return prop;
}

@Bean
public JpaTransactionManager transactionManager(){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}

@Bean
public SchedulerFactoryBean schedulerFactoryBean(){
return new SchedulerFactoryBean();
}

@Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(104857600);
return resolver;
}

@Bean
public LocalValidatorFactoryBean validator(){
return new LocalValidatorFactoryBean();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
* Created by Administrator on 2015/12/25.
*/

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.mediaType("json", MediaType.valueOf("application/json"));
configurer.mediaType("xml",MediaType.valueOf("application/xml"));
configurer.mediaType("html",MediaType.valueOf("text/html"));
configurer.mediaType("*",MediaType.valueOf("*/*"));
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
List<MediaType> list = new ArrayList<MediaType>();
list.add(new MediaType("text","plain",Charset.forName("UTF-8")));
list.add(new MediaType("*","*",Charset.forName("UTF-8")));
stringConverter.setSupportedMediaTypes(list);

FastJsonHttpMessageConverter jsonConverter = new FastJsonHttpMessageConverter();
List<MediaType> jsonList = new ArrayList<MediaType>();
jsonList.add(MediaType.valueOf("application/json;charset=UTF-8"));
jsonList.add(MediaType.valueOf("text/plain;charset=utf-8"));
jsonList.add(MediaType.valueOf("text/html;charset=utf-8"));
jsonConverter.setSupportedMediaTypes(jsonList);
jsonConverter.setFeatures(new SerializerFeature[]{SerializerFeature.WriteDateUseDateFormat});

converters.add(stringConverter);
converters.add(jsonConverter);
}
}

这两个类就包含了spring-mvc.xml,spring-root.xml等相关配置。其中MvcConfig包含了对json的支持。
本处引用了db.properties,内容和上一篇一致。
其他的实现与上一篇文章一致。

源码可以到springmvc_noxml下载。

热评文章