spring+springmvc+maven+mongodb
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- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.tl.project</groupId>
- <artifactId>skyLine</artifactId>
- <packaging>war</packaging>
- <version>1.0-SNAPSHOT</version>
- <name>skyLine Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <!--建議我所引用包的版本集中放在這裏,這樣比較直觀-->
- <properties>
- <spring.version>4.2.5.RELEASE</spring.version>
- <aspectj.version>1.8.9</aspectj.version>
- <cglib.version>3.2.4</cglib.version>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <!--<version>3.8.1</version>-->
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</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>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</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.8.4.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>
- <build>
- <finalName>skyLine</finalName>
- <plugins>
- <!-- 編碼和編譯和JDK版本 -->
- <!--解決@Override not allowed when implementing interface method報錯問題-->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.3.2</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- <encoding>utf8</encoding>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
3.2.2 spring-context.xml
[java] view plain copy- <?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://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd">
- <!--開啟註解處理器-->
- <!--<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
[java] view plain copy- <?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://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd">
- <!--只在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
[java] view plain copy- <?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>
3.2.5 config.properties
[java] view plain copy- #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在控制臺增加報錯日誌信息,方便項目搭建的時候調試用的:
[java] view plain copy- 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
這個是項目打印日誌信息用的,也可配置打印在控制臺,或者打印在硬盤某個路徑下的文檔裏:
[java] view plain copy- #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去掉,這樣就不會顯示日誌發生的位置,不會打印類名,方法名了;
[java] view plain copy- %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
[java] view plain copy
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="3.0"
- 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_3_0.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>
- <!--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>
- <!--Spring log4j Config loader-->
- <listener>
- <listener-class>
- org.springframework.web.util.Log4jConfigListener
- </listener-class>
- </listener>
- <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>-->
- <!--通過 EnvironmentLoaderListener 這個監聽器來初始化 SecurityManager-->
- <!--<listener>-->
- <!--<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</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>
3.3 User類
[java] view plain copy- 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
[java] view plain copy- 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);
- }
userDaoImpl
[java] view plain copy- 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);
- }
- }
- }
3.5單元測試
[java] view plain copy- 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());
- }
- }
至此,基本的項目骨架就搭成了!
整個過程有些很多東西也是參考網上的博客,也結合自己的項目搭建起來的,萬丈高樓平地起,再大的項目也是一點點的搭建,不斷的測試,完善才完成的,在搭建項目的過程中收獲了很多,當然這個項目只是第一步,自己會不斷的完善!
另附整個項目的結構:
spring+springmvc+maven+mongodb