1.前言
最近项目开发使用到了spring+springmvc+maven+MongoDB,项目中的框架是用springboot进项开发的,对于我们中级开发人员来说,有利有弊,好处呢是springboot开发减少了很多配置文件,同时也使开发更加规范快捷,但是,不好的地方就是长此以往,我们就在码农的道路上越走越远。。。
所以,为了抵制码农的身份,在工作之余自己亲手由零一点一点搭建了这个框架,当然框架暂时只包含基本的东西,但是千里之行始于足下,良好的开始就是成功的一半,我会在以后的道路上不断进行扩展的,如果有问题,也请大家不吝赐教,我们共同进步!
2.准备环境
工欲善其事必先利其器,我们先做好前期准备工作,开发工具IntelliJ IDEA14,jdk版本是1.8,对于Java环境变量配置,mongodb的安装,maven的这边不做过多说明,网上也有很多详细的说明,大家可以去查询,那么下面我们就开始项目的搭建。
3.项目搭建
3.1创建maven项目
详细步骤 点击这里
3.2 配置文件
3.2.1 maven依赖
[java] view plain copy
- <span style="font-size:14px;"><dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>4.0.5.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>3.2.11.RELEASE</version>
- <scope>compile</scope>
- <!--<exclusions>-->
- <!--<exclusion>-->
- <!--<groupId>commons-logging</groupId>-->
- <!--<artifactId>commons-logging</artifactId>-->
- <!--</exclusion>-->
- <!--</exclusions>-->
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>4.0.5.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>3.2.11.RELEASE</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>4.0.5.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>4.0.5.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>3.2.3.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.2.7</version>
- </dependency>
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.30</version>
- </dependency>
- <!-- mongoDB支持jar -->
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-mongodb</artifactId>
- <version>1.2.0.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <version>3.1.0</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet.jsp</groupId>
- <artifactId>jsp-api</artifactId>
- <version>2.1</version>
- <scope>provided</scope>
- </dependency>
- <!--JSP标准标签库(JSTL)-->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <dependency>
- <groupId>dom4j</groupId>
- <artifactId>dom4j</artifactId>
- <version>1.6.1</version>
- </dependency>
- <!--区别slf4j与log4j-->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>jcl-over-slf4j</artifactId>
- <version>1.7.7</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.7</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-nop</artifactId>
- <version>1.7.5</version>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
- </dependencies>
- </span>
3.2.2 spring-context.xml
[java] view plain copy
- <span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
- <!--开启注解处理器-->
- <!--<context:annotation-config/>-->
- <!-- 自动检测bean,启用spring mvc 注解@Autowired,@Resource,@Required等 <context:annotation-config /> 有了下面扫描配置后该项可以省掉-->
- <!--<context:component-scan base-package="com.tl.skyLine">-->
- <!--<!– 排除不扫描的 –>-->
- <!--<!–<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>–>-->
- <!--</context:component-scan>-->
- <!--导入mongodb的配置文件-->
- <import resource="mongodb-context.xml"/>
- <!--仅用来测试springIoc是否成功-->
- <bean id="test" class="com.tl.skyLine.TestSpringIocController">
- </bean>
- </beans></span>
3.2.3 springmvc-servlet.xml
[java] view plain copy
- <span style="font-size:14px;"><?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:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
- <!-- 启用spring mvc 注解 -->
- <!--<context:annotation-config />-->
- <!--自定扫描package中的注解-->
- <!--有了这一句,上面的<context:annotation-config />可以省略-->
- <context:component-scan base-package="com.tl.skyLine"/>
- <!-- 默认的注解映射的支持,自动注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
- <!--<mvc:annotation-driven />-->
- <!-- 将在Controller返回的ModelAndView,加上目录前缀/WEB-INF/views/, 文件名称后缀.jsp -->
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
- <!--<beans:property name="prefix" value="/WEB-INF/views/"/>-->
- <property name="prefix" value="/pages/"/>
- <property name="suffix" value=".jsp"/>
- </bean>
- <!-- 对静态资源文件的访问-->
- <!--<mvc:resources mapping="/images/**" location="/WEB-INF/images/" cache-period="31556926"/>-->
- <!--<mvc:resources mapping="/js/**" location="/WEB-INF/js/" cache-period="31556926"/>-->
- <!--<mvc:resources mapping="/css/**" location="/WEB-INF/css/" cache-period="31556926"/>-->
- </beans></span>
3.2.4 mongodb-context.xml
[java] view plain copy
- <span style="font-size:14px;"><?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:mongo="http://www.springframework.org/schema/data/mongo"
- xsi:schemaLocation="http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/data/mongo
- http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <!-- 加载mongodb的属性配置文件 -->
- <context:property-placeholder location="classpath:config.properties"/>
- <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
- <mongo:mongo id="mongo" replica-set="${mongo.hostport}">
- <!-- 一些连接属性的设置 -->
- <mongo:options
- connections-per-host="${mongo.connectionsPerHost}"
- threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
- connect-timeout="${mongo.connectTimeout}"
- max-wait-time="${mongo.maxWaitTime}"
- auto-connect-retry="${mongo.autoConnectRetry}"
- socket-keep-alive="${mongo.socketKeepAlive}"
- socket-timeout="${mongo.socketTimeout}"
- slave-ok="${mongo.slaveOk}"
- write-number="1"
- write-timeout="0"
- write-fsync="true"/>
- </mongo:mongo>
- <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
- <mongo:db-factory dbname="skyLine" mongo-ref="mongo"/>
- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
- <constructor-arg ref="mongo"/>
- <constructor-arg name="databaseName" value="${mongo.database}"/>
- </bean>
- <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
- <mongo:mapping-converter base-package="com.tl.skyLine.model"/>
- <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
- <mongo:repositories base-package="com.tl.skyLine.repository"/>
- </beans></span>
3.2.5 config.properties
[java] view plain copy
- <span style="font-size:14px;">#mongoDB连接配置
- mongo.hostport=127.0.0.1:27017
- mongo.connectionsPerHost=8
- mongo.threadsAllowedToBlockForConnectionMultiplier=4
- #连接超时时间
- mongo.connectTimeout=1000
- #等待时间
- mongo.maxWaitTime=1500
- mongo.autoConnectRetry=true
- mongo.socketKeepAlive=true
- #Socket超时时间
- mongo.socketTimeout=1500
- mongo.slaveOk=true
- #数据库名称
- mongo.database=skyLine</span>
3.2.6 web.xml
[java] view plain copy
- <span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <!--指定欢迎页面-->
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <!--真正的加载顺序为:context-param -> listener -> filter -> servlet-->
- <!--<listener>-->
- <!--<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>-->
- <!--</listener>-->
- <!--1、在web.xml配置监听器ContextLoaderListener-->
- <!--ContextLoaderListener的作用(一句话):初始化BeanFactory,并将BeanFactory设置到application中。-->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!--Spring log4j Config loader-->
- <listener>
- <listener-class>
- org.springframework.web.util.Log4jConfigListener
- </listener-class>
- </listener>
- <!--2、部署applicationContext的xml文件,默认的路径是"/WEB-INF/applicationContext.xml,
- 如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:
- 在<param-value> </param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并以“,”号分隔。
- 也可以这样applicationContext-*.xml采用通配符,-->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring-context.xml</param-value>
- </context-param>
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>classpath:log4j.properties</param-value>
- </context-param>
- <!-- 防止Spring内存溢出监听器 -->
- <!--<listener>-->
- <!--<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>-->
- <!--</listener>-->
- <!--使用Spring MVC,配置DispatcherServlet是第一步。DispatcherServlet是一个Servlet,
- 所以可以配置多个DispatcherServlet-->
- <servlet>
- <servlet-name>springMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:springmvc-servlet.xml</param-value>
- </init-param>
- <!--是启动顺序,让这个Servlet随Servletp容器一起启动。-->
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springMVC</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <!-- 在Spring框架中是如何解决从页面传来的字符串的编码问题的呢?
- 下面我们来看看Spring框架给我们提供过滤器CharacterEncodingFilter
- 这个过滤器就是针对于每次浏览器请求进行过滤的,然后再其之上添加了父类没有的功能即处理字符编码。
- 其中encoding用来设置编码格式,forceEncoding用来设置是否理会 request.getCharacterEncoding()方法,设置为true则强制覆盖之前的编码格式。-->
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.html</url-pattern>
- </servlet-mapping>
- <error-page> <!--当系统出现404错误,跳转到页面nopage.html-->
- <error-code>404</error-code>
- <location>/noPage.jsp</location>
- </error-page>
- <session-config><!--会话超时配置,单位分钟-->
- <session-timeout>360</session-timeout>
- </session-config>
- </web-app>
- </span>
3.3 User类
[java] view plain copy
- <span style="font-size:14px;">package com.tl.skyLine.model;
- import org.springframework.data.annotation.Id;
- import org.springframework.data.mongodb.core.mapping.Document;
- /**
- * 系统操作人员
- */
- @Document(collection = "sky.user")
- public class User {
- @Id
- private String id;
- private String username;
- private String password;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
- </span>
3.4 数据层操作dao
userDao
[java] view plain copy
- <span style="font-size:14px;">package com.tl.skyLine.repository;
- import com.tl.skyLine.model.User;
- import java.util.List;
- /**
- * UserDao
- * Created by tl on 17/2/13.
- */
- public interface UserDao {
- /**
- * 查询所有数据
- *
- * @return
- */
- List<User> findAll();
- /**
- * 用于分页查询
- *
- * @param skip(第一个坐标为0)
- * @param limit
- * @return
- */
- List<User> findList(int skip, int limit);
- /**
- * 保存用户
- *
- * @param user
- */
- void store(User user);
- /**
- * 根据id查询
- *
- * @param id
- * @return
- */
- User findOne(String id);
- /**
- * 根据用户名查询
- *
- * @param username
- * @return
- */
- User findOneByUsername(String username);
- /**
- * 更新
- *
- * @param user
- */
- void updateFirst(User user);
- /**
- * 删除
- *
- * @param ids
- */
- void delete(String... ids);
- }
- </span>
userDaoImpl
[java] view plain copy
- <span style="font-size:14px;">package com.tl.skyLine.repository;
- import com.tl.skyLine.model.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.domain.Sort;
- import org.springframework.data.domain.Sort.Direction;
- import org.springframework.data.domain.Sort.Order;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.data.mongodb.core.query.Criteria;
- import org.springframework.data.mongodb.core.query.Query;
- import org.springframework.data.mongodb.core.query.Update;
- import org.springframework.stereotype.Service;
- import java.util.List;
- /**
- * UserDaoImpl
- * Created by tl on 17/2/13.
- */
- @Service
- public class UserDaoImpl implements UserDao {
- //MongoTemplate是数据库和代码之间的接口,对数据库的操作都在它里面
- @Autowired
- private MongoTemplate mongoTemplate;
- @Override
- public List<User> findAll() {
- return this.mongoTemplate.find(new Query(), User.class);
- }
- @Override
- public List<User> findList(int skip, int limit) {
- Query query = new Query();
- query.with(new Sort(new Order(Direction.ASC, "_id")));
- query.skip(skip).limit(limit);
- return this.mongoTemplate.find(query, User.class);
- }
- @Override
- public void store(User user) {
- mongoTemplate.save(user);
- }
- /**
- * Criteria.where("username").is(username)
- * 前一个是数据库的字段,后一个是java类的字段
- *
- * @param username
- * @return
- */
- @Override
- public User findOneByUsername(String username) {
- Query query = new Query();
- Criteria criteria = Criteria.where("username").is(username);
- query.addCriteria(criteria);
- return this.mongoTemplate.findOne(query, User.class);
- }
- @Override
- public User findOne(String id) {
- Query query = new Query();
- Criteria criteria = Criteria.where("_id").is(id);
- query.addCriteria(criteria);
- return this.mongoTemplate.findOne(query, User.class);
- }
- @Override
- public void updateFirst(User user) {
- Update update = new Update();
- Query query = new Query();
- update.set("username", user.getUsername());
- update.set("password", user.getPassword());
- this.mongoTemplate.updateFirst(query.addCriteria(Criteria.where("_id").is(user.getId())), update, User.class);
- }
- @Override
- public void delete(String... ids) {
- if (ids == null || ids.length == 0) {
- return;
- }
- for (String id : ids) {
- Query query = new Query(Criteria.where("_id").is(id));
- this.mongoTemplate.remove(query, User.class);
- }
- }
- }
- </span>
3.5单元测试
[java] view plain copy
- <span style="font-size:14px;">package com.tl.skyLine.controller;
- import com.tl.skyLine.TestSpringIocController;
- import com.tl.skyLine.model.User;
- import com.tl.skyLine.repository.UserDao;
- import org.apache.log4j.Logger;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import javax.annotation.Resource;
- import java.util.List;
- /**
- * 测试springIoc是否成功
- * Created by tl on 17/2/11.
- * <p/>
- * 注解@ContextConfiguration表示将ApplicationContext对象注入进来,就不用像以往那样在测试程序里先new了,直接使用
- */
- @RunWith(SpringJUnit4ClassRunner.class)
- //@ContextConfiguration(locations = "classpath:spring-context.xml")
- @ContextConfiguration(locations = {"classpath:spring-context.xml", "classpath:springmvc-servlet.xml"})
- public class UserDaoTestController {
- // 在任何需要记录日志的类中
- private static Logger logger = Logger.getLogger(UserDaoTestController.class);
- @Resource
- private UserDao userDao;
- /**
- * 测试Spring IOC的开发环境
- */
- @Test
- public void springIoc() {
- ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
- TestSpringIocController test = (TestSpringIocController) context.getBean("test");
- test.print();
- }
- @Test //测试Spring IOC的开发环境
- public void save() {
- User user = new User();
- user.setUsername("skyLine2");
- user.setPassword("7777777");
- userDao.store(user);
- User user2 = userDao.findOneByUsername("skyLine2");
- logger.info("-------获取账户密码:-------" + user2.getPassword());
- }
- @Test
- public void update() {
- User user = userDao.findOneByUsername("skyLine2");
- logger.info("-------更新之前账户密码:-------" + user.getPassword());
- user.setPassword("9999888");
- userDao.updateFirst(user);
- logger.info("-------更新之后账户密码:-------" + user.getPassword());
- }
- @Test //测试Spring IOC的开发环境
- public void findAll() {
- // List<User> lists = userDao.findAll();
- // for (User user : lists) {
- // logger.info("-------user遍历:-------" + user.getUsername());
- // }
- List<User> lists2= userDao.findList(1,2);
- for (User user : lists2) {
- logger.info("-------user遍历:-------" + user.getUsername());
- }
- }
- @Test
- public void delete() {
- userDao.delete(userDao.findOneByUsername("skyLine2").getId());
- }
- }
- </span>
至此,基本的项目骨架就搭成了!
整个过程有些很多东西也是参考网上的博客,也结合自己的项目搭建起来的,万丈高楼平地起,再大的项目也是一点点的搭建,不断的测试,完善才完成的,在搭建项目的过程中收获了很多,当然这个项目只是第一步,自己会不断的完善!