出来工作都有一年了,做过不少项目,大多数都是以springmvc为基础,每次搭建项目的时候,都特别烦xml,但是有没有什么好的办法。最近有空看了下资料,springmvc早已经出了零配置xml构建工程方法。在网上找了下资料,发现挺简单,自己动手来玩玩下。
需要用的技术 spring 5 mvc做web mvc框架,spring5 data jpa 做持久层,druid做连接池依赖,fastjson做jsonMessageConverter。
项目用maven构建 pom.xml依赖如图:
配置DispatcherServlet
随着Servlet 3.0规范的发布,可以用几乎没有xml来配置你的Servlet容器。为此ServletContainerInitializer,在Servlet规范中有。在这个类中,你可以注册过滤器,监听器,servlet等,就像你在传统上做的那样web.xml。
Spring提供了SpringServletContainerInitializer知道如何处理WebApplicationInitializer类的东西。AbstractAnnotationConfigDispatcherServletInitializer类实现WebMvcConfigurer内部实现WebApplicationInitializer。它注册一个ContextLoaderlistener(可选的)和一个,DispatcherServlet并允许您轻松地添加配置类来加载这两个类,并将过滤器应用于DispatcherServlet和提供servlet映射。
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class[] getRootConfigClasses() {
return new Class[] { AppConfig.class};
}
@Override
protected Class[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[] {WebMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
}
@Override
public void onStartup(ServletContext servletContext)throws ServletException{
super.onStartup(servletContext);
CharacterEncodingFilter chEncodingFilter = new CharacterEncodingFilter();
Dynamic dynamic = servletContext.addFilter("chEncodingFilter",chEncodingFilter);
dynamic.setInitParameter("encoding", "UTF-8");
dynamic.setInitParameter("forceEncoding","true");
dynamic.addMappingForUrlPatterns(null, false, "/*");
//添加阿里云druid的数据库监控
StatViewServlet statViewServlet = new StatViewServlet();
javax.servlet.ServletRegistration.Dynamic servlet = servletContext.addServlet("statViewServlet", statViewServlet); servlet.addMapping("/druid/*");
}
Spring WebMVC配置
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.ting.spring.core", useDefaultFilters = false, includeFilters = @Filter(type = FilterType.ANNOTATION, value = { Controller.class }))
public class WebMvcConfig implements WebMvcConfigurer {
/** * 设置mvc 前缀 后缀 * * @return */
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
/** * 设置配置文件的前缀 * * @return */
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("applicationContext");
return source;
}
/* * @Override public Validator getValidator() {
LocalValidatorFactoryBean * factoryBean = new LocalValidatorFactoryBean();
return factoryBean; } */
@Bean
public FastJsonHttpMessageConverter converter() {
FastJsonHttpMessageConverter jsonMessageConverter = new FastJsonHttpMessageConverter();
jsonMessageConverter.setDateFormat("yyyy-MM-dd hh:mm:ss");
jsonMessageConverter.setFeatures(SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteDateUseDateFormat);
List supportedMediaTypes = new ArrayList(); supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
jsonMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
return jsonMessageConverter;
}
/** * 添加静态资源映射 */
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**", "/js/**", "/css/**"); }
@Bean public DemoInterceptor initIntercepter() {
return new DemoInterceptor();
}
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(initIntercepter());
}
//主要这一步是必须的,不然会出现类型转换。。
@Override
public void configureMessageConverters(List> converters) {
converters.add(converter());
}
}
spring data jpa配置
@EnableTransactionManagement
@Configuration
@PropertySource("classpath:applicationContext.properties") @ComponentScan(basePackages = "com.ting.spring.core", excludeFilters = { @Filter(value = {EnableWebMvc.class,Controller.class}) }) @EnableJpaRepositories(basePackages = "com.ting.spring.core.dao",entityManagerFactoryRef= "emf")
public class AppConfig {
@Autowired
private Environment env;
@Bean(name = "emf")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(getDataSource()); bean.setPackagesToScan("com.ting.spring.core.model");
JpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); bean.setJpaVendorAdapter(adapter);
bean.setJpaProperties(createProp());
return bean;
}
@Bean
public DataSource getDataSource() {
//DriverManagerDataSource dataSource = new DriverManagerDataSource();
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(env.getProperty("jdbc.mysql.username"));
dataSource.setUrl(env.getProperty("jdbc.mysql.url"));
dataSource.setPassword(env.getProperty("jdbc.mysql.password"));
dataSource.setDriverClassName(env.getProperty("jdbc.mysql.driver"));
dataSource.setMaxActive(Integer.parseInt(String.valueOf(env.getProperty("jdbc.maxActive"))));
dataSource.setInitialSize(env.getProperty("jdbc.initialSize", Integer.class));
dataSource.setMaxWait(env.getProperty("jdbc.maxWait", Integer.class));
dataSource.setMinIdle(env.getProperty("jdbc.minIdle", Integer.class));
dataSource.setMaxIdle(env.getProperty("jdbc.maxIdle", Integer.class));
dataSource.setTimeBetweenEvictionRunsMillis(env.getProperty("jdbc.timeBetweenEvictionRunsMillis", Long.class)); try {
dataSource.setFilters(env.getProperty("jdbc.filters"));
} catch (SQLException e) {
// TODO Auto-generated catch block e.printStackTrace();
} return dataSource;
}
@Bean public PlatformTransactionManager transactionManager(EntityManagerFactory enFactory) {
JpaTransactionManager jManager = new JpaTransactionManager();
jManager.setEntityManagerFactory(enFactory); return jManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
public Properties createProp() {
Properties properties = new Properties(); properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
}
实体类
@Entity
@Table(name = "user_info")
@ToString
@Data
public class UserInfo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "user_name")
private String userName;
private Integer age;
private String phone;
private String sex;
private String email;
@Column(name = "create_time")
private Date ctime;
}
service层和Dao
@Service
public class UserInfoService {
@Autowired private UserInfoDao userDao;
public List findAll(){
return userDao.findAll();
}
}
@Repository
public interface UserInfoDao extends JpaRepository{ }
控制层
@Controller
public class IndexController {
@Autowired private UserInfoService userService;
private static Logger log = Logger.getLogger(IndexController.class); @GetMapping("/index")
public String index() {
log.info("hello 。。。。。");
return "index";
}
/**
*服务器sse推送
*/
@GetMapping(value="/push",produces="text/event-stream;charset=UTF-8") @ResponseBody
public String push() throws Exception {
Random r = new Random();
Thread.sleep(2000);
return new String("data:\n\n".getBytes(),"utf-8"); }
@GetMapping("user/list")
@ResponseBody public Object findAll() {
return userService.findAll();
}
}
整个目录架构
一般都是周末才有时间发帖,平常下班也没什么时间,一直都不是很清楚这个富文本框怎么用?如果有谁知道怎么让代码格式化更好看点,麻烦告诉我一声,有时间我会发更多学习帖子和大家分享!最后分享一个我构建工程主要参照帖子:spring5 example