1.前言
最近項目開發使用到了spring+springmvc+maven+mongodb,項目中的框架是用springboot進項開發的,對於咱們中級開發人員來講,有利有弊,好處呢是springboot開發減小了不少配置文件,同時也使開發更加規範快捷,可是,很差的地方就是久而久之,咱們就在碼農的道路上越走越遠。。。css
因此,爲了抵制碼農的身份,在工做之餘本身親手由零一點一點搭建了這個框架,固然框架暫時只包含基本的東西,可是千里之行始於足下,良好的開始就是成功的一半,我會在之後的道路上不斷進行擴展的,若是有問題,也請你們不吝賜教,咱們共同進步!html
2.準備環境
工欲善其事必先利其器,咱們先作好前期準備工做,開發工具IntelliJ IDEA14,jdk版本是1.8,對於java環境變量配置,mongodb的安裝,maven的這邊不作過多說明,網上也有不少詳細的說明,你們能夠去查詢,那麼下面咱們就開始項目的搭建。java
3.項目搭建
3.1建立maven項目
詳細步驟 點擊這裏mysql
3.2 配置文件
3.2.1 maven依賴
3.2.2 spring-context.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:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http:
- http:
- http:
- http:
- http:
- http:
-
- <!--開啓註解處理器-->
- <!--<context:annotation-config/>-->
-
- <!-- 自動檢測bean,啓用spring mvc 註解@Autowired,@Resource,@Required等
- <context:annotation-config /> 有了下面掃描配置後該項能夠省掉-->
- <context:component-scan base-package="com.tl.skyLine">
- <!-- 排除不掃描的,controller放在子容器springmvc的配置文件中 -->
- <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.controller.TestSpringIocController">
- </bean>
- </beans>
3.2.3 springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http:
- http:
- http:
- http:
- http:
- http:
-
- <!--只在springmvc容器中配置controller的掃描-->
- <context:component-scan base-package="com.tl.skyLine" use-default-filters="false">
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
-
- <!--這個是SpringMVC必需要配置的,由於它聲明瞭@RequestMapping、@RequestBody、@ResponseBody等。而且,該配置默認加載不少的參數綁定方法,好比json轉換解析器等。-->
- <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"/>-->
-
- <!--因爲父子容器的關係,@controller註解掃描配置在mvc中,因此啓動shiro註解也須要在子容器中引用一次-->
- <import resource="shiro-context.xml"/>
-
- </beans>
3.2.4 mongodb-context.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:context="http://www.springframework.org/schema/context"
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"
- xsi:schemaLocation="http:
- http:
- http:
- http:
- http:
- http:
- <!-- 加載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>
3.2.5 config.properties
- #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
3.2.7 logging.properties
這個主要是爲tomcat在控制檯增長報錯日誌信息,方便項目搭建的時候調試用的:web
- handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
-
- ############################################################
- # Handler specific properties.
- # Describes specific configuration info for Handlers.
- ############################################################
-
- org.apache.juli.FileHandler.level = FINE
- org.apache.juli.FileHandler.directory = ${catalina.base}/logs
- org.apache.juli.FileHandler.prefix = error-debug.
-
- java.util.logging.ConsoleHandler.level = FINE
- java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
3.2.8 log4j.properties
這個是項目打印日誌信息用的,也可配置打印在控制檯,或者打印在硬盤某個路徑下的文檔裏:spring
- #rootCategory:默認是對整個工程生效
- log4j.rootCategory=INFO, stdout
- #日誌輸出級別,日誌信息的優先級從高到低有ERROR、WARN、 INFO、DEBUG
- log4j.rootLogger=info, stdout
-
- ### stdout ###
- #設置stdout的日誌輸出控制檯
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- #輸出日誌到控制檯的方式,默認爲System.out
- log4j.appender.stdout.Target=System.out
- #設置使用靈活佈局
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- #靈活定義輸出格式
- log4j.appender.stdout.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}] %l %m %n
-
-
- #設置other的日誌輸出控制檯
- log4j.appender.other=org.apache.log4j.RollingFileAppender
- #設置other的輸出日誌
- log4j.appender.other.File=${webapp.root}/WEB-INF/logs/log.log
- #設置other的日誌最大限制
- log4j.appender.other.MaxFileSize=1024KB
- #最多隻保存20個備份文件
- log4j.appender.other.MaxBackupIndex=1000
- #輸出INFO級別以上的日誌
- og4j.appender.other.Threshold=INFO
- #設置使用靈活佈局
- log4j.appender.other.layout=org.apache.log4j.PatternLayout
- #靈活定義輸出格式
- log4j.appender.other.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}] %l %t %m %n
輸出格式能夠本身定義,咱們上面定義的比較多,若是以爲控制檯打印內容過於繁瑣,能夠根據需求修改,好比若是把%l去掉,這樣就不會顯示日誌發生的位置,不會打印類名,方法名了;sql
- %m 輸出代碼中指定的消息
- %p 輸出優先級,即DEBUG,INFO,WARN,ERROR,FATAL
- %r 輸出自應用啓動到輸出該log信息耗費的毫秒數
- %c 輸出所屬的類目,一般就是所在類的全名
- %t 輸出產生該日誌事件的線程名
- %n 輸出一個回車換行符,Windows平臺爲「/r/n」,Unix平臺爲「/n」
- %d 輸出日誌時間點的日期或時間,默認格式爲ISO8601,也能夠在其後指定格式,好比:%d{yyy MMM dd HH:mm:ss , SSS},輸出相似:2002年10月18日 22 : 10 : 28 , 921
- %l 輸出日誌事件的發生位置,包括類目名、發生的線程,以及在代碼中的行數。舉例:Testlog4.main(TestLog4.java: 10 )
3.2.9 web.xml
3.3 User類
- 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;
- }
- }
3.4 數據層操做dao
userDao
- package com.tl.skyLine.repository;
-
- import com.tl.skyLine.model.User;
-
- import java.util.List;
-
- public interface UserDao {
-
-
- List<User> findAll();
-
-
- List<User> findList(int skip, int limit);
-
-
- void store(User user);
-
-
- User findOne(String id);
-
-
- User findOneByUsername(String username);
-
-
- void updateFirst(User user);
-
-
- void delete(String... ids);
- }
userDaoImpl
- 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;
-
- @Service
- public class UserDaoImpl implements UserDao {
-
-
- @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);
- }
-
-
- @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);
- }
- }
- }
3.5單元測試
- 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;
-
- @RunWith(SpringJUnit4ClassRunner.class)
- @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;
-
-
- @Test
- public void springIoc() {
- ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
- TestSpringIocController test = (TestSpringIocController) context.getBean("test");
- test.print();
- }
-
- @Test
- 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
- public void findAll() {
-
- 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());
- }
-
- }
至此,基本的項目骨架就搭成了!mongodb
整個過程有些不少東西也是參考網上的博客,也結合本身的項目搭建起來的,萬丈高樓平地起,再大的項目也是一點點的搭建,不斷的測試,完善才完成的,在搭建項目的過程當中收穫了不少,固然這個項目只是第一步,本身會不斷的完善!數據庫
另附整個項目的結構: