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依赖
<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
<?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
<?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
<?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
#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在控制台增加报错日志信息,方便项目搭建的时候调试用的:
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
这个是项目打印日志信息用的,也可配置打印在控制台,或者打印在硬盘某个路径下的文档里:
#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去掉,这样就不会显示日志发生的位置,不会打印类名,方法名了;
%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
<?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类
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;
/**
* 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
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单元测试
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());
}
}
至此,基本的项目骨架就搭成了!
整个过程有些很多东西也是参考网上的博客,也结合自己的项目搭建起来的,万丈高楼平地起,再大的项目也是一点点的搭建,不断的测试,完善才完成的,在搭建项目的过程中收获了很多,当然这个项目只是第一步,自己会不断的完善!