Part 3 - 1. Project Configuration
In this post, the steps of configuring the project is introduced.
Step 1: Create a project with required directory structure
The important folders include sources root
and resources root
Step 2: Import dependencies in pom.xml
Include junit, mybatis, mybits-spring, mybatis-generator-core, mysql-connector-java, c3p0, spring-context, spring-test, spring-beans, spring-webmvc, spring-jdbc, spring-aspects, jstl, javax.servelt-api, jsqlparser, log4j, commons-logging, commons-fileupload, commons-io, commons-lang, aopalliance.
Note: the versions of these dependencies may have conflicts.
The code is as follows.
CLICK ME
4.0.0
com.example.tmall
tmall
1.0-SNAPSHOT
war
4.1.3.RELEASE
5.1.2-beta
5.1.47
1.3.1
3.4.2
4.12
1.2
1.0
1.2.7
3.1.0
1.0.18
1.2.16
1.2
1.2.1
1.3.2
2.6
1.0
1.3.5
junit
junit
${junit.version}
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
${mybatis.spring.version}
mysql
mysql-connector-java
${mysql.version}
c3p0
c3p0
0.9.1.2
org.springframework
spring-context
${spring.version}
org.springframework
spring-test
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-aspects
${spring.version}
jstl
jstl
${jstl.version}
javax.servlet
javax.servlet-api
${servlet-api.version}
provided
com.github.pagehelper
pagehelper
${pagehelper.version}
com.github.jsqlparser
jsqlparser
${jsqlparser.version}
log4j
log4j
${log4j.version}
commons-logging
commons-logging
${commons-logging.version}
commons-fileupload
commons-fileupload
${commons-fileupload.version}
commons-io
commons-io
${commons-io.version}
commons-lang
commons-lang
${commons-lang.version}
aopalliance
aopalliance
${aopalliance.version}
org.mybatis.generator
mybatis-generator-core
${mybatis-generator.version}
${project.artifactId}
org.apache.maven.plugins
maven-resources-plugin
2.7
UTF-8
org.apache.maven.plugins
maven-compiler-plugin
3.2
org.apache.tomcat.maven
tomcat7-maven-plugin
2.2
src/main/resources
**/*.properties
**/*.xml
**/*.tld
false
src/main/java
**/*.properties
**/*.xml
false
Step 2. Configure Tomcat
Include server
and deployment
.
Step 3. Config Log4j
Create a file named Log4j.properties
under resources
folder
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.example.tmall=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Step 4. Configure jdbc
Create a file named jdbc.properties
under resources
folder
Specify drive
, url
, username
, password
.
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/tmall?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
Step 5. Configure Mybitis
Include useGeneratedKeys
, useColumnLabel
and mapUnderscoreToCamelCase
.
Step 6. Configure Spring JDBC Connection
We create a spring configuration file named spring-dao.xml
under /resources/spring
folder.
In this file, we mainly config spring jdbc.
- 6.1: Add context schema in the head line, i.e.
xmlns:context="http://www.springframework.org/schema/context"
- Import basic jdbc configuration file, i.e.
jdbc.properties
<context:property-placeholder location="classpath:jdbc.properties"/>
- 6.2: Configure jdbc connection pool. To be specific, create a bean named
dataSource
, where we set properties ofc3p0
connection pool.
The most straightforward way to create a c3p0 pooling DataSource
is to instantiate an instance of com.mchange.v2.c3p0.ComboPooledDataSource
. This is a JavaBean-style class with a public, no-arg constructor, but before you use the DataSource, you’ll have to be sure to set at least the property jdbcUrl. You may also want to set user and password, and, if you use an old-style JDBC driver that you will not externally preload, you should set the driverClass.
Why use connection pools? link
c3p0 - JDBC3 Connection and Statement Pooling- 6.3: Build a
SqlSessionFactory instance
from an XML file, set properties, e.g.typeAliasesPackage
,dataSource
,configLocation
,mapperLocations
.- typeAliasesPackage: A type alias is a shorter name for a Java type, to reduce redundante typing of fully qualified classnames. You can also specify a package where MyBatis will search for beans.
- dataSource: configures the source of JDBC Conntection objexts using standard JDBC DataSource interface.
- configLocation: tell MyBatis where to find configuration file.
- mapperLocation: tell MyBatis where to find mapped SQL statements.
Whenever we have a sqlSesstionFactory
, we can create sqlSessions
. The sqlSession
then executes SQL Statements
.
Scope and Lifecycle
sourceSqlSessionFactoryBuilder
This class can be instantiated, used and thrown away. There is no need to keep it around once you’ve created your SqlSessionFactory
. Therefore the best scope for instances of SqlSessionFactoryBuilder is method scope (i.e. a local method variable). You can reuse the SqlSessionFactoryBuilder
to build multiple SqlSessionFactory instances, but it’s still best not to keep it around to ensure that all of the XML parsing resources are freed up for more important things.
SqlSessionFactory
Once created, the SqlSessionFactory
should exist for the duration of your application execution. There should be little or no reason to ever dispose of it or recreate it. It’s a best practice to not rebuild the SqlSessionFactory multiple times in an application run. Therefore the best scope of SqlSessionFactory is application scope. This can be achieved a number of ways. The simplest is to use a Singleton pattern or Static Singleton pattern.
SqlSession
Each thread
should have its own instance of SqlSession
. Instances of SqlSession are not to be shared and are not thread safe. Therefore the best scope is request or method scope. Never keep references to a SqlSession instance in a static field or even an instance field of a class. Never keep references to a SqlSession in any sort of managed scope, such as HttpSession of the Servlet framework. If you’re using a web framework of any sort, consider the SqlSession to follow a similar scope to that of an HTTP request. In other words, upon receiving an HTTP request, you can open a SqlSession, then upon returning the response, you can close it. Closing the session is very important. You should always ensure that it’s closed within a finally block.
- 6.4: Regist a mapper in spring, i.e. create a bean named
MapperScannerConfigurer
, specifysqlSessionFactoryBeanName
,basePackage
basePackage
: let you set the base package for your mapper interface files.sqlSessionFactoryBeanName
: specify a specificsqlSessionFactory
.
The whole code in spring-dao.xml
is as follows.
CLICK ME
Step 7. spring-service configuration
- 7.1: Add context and transaction (i.e tx) schema in the head line, i.e.
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx
- 7.2: Configure scanner location
- 7.3: Configure
transactionManager
When using transaction management in Spring, we need to definetransactionManager
. Typically we can define this through dependency injection. The related bean definition will then have a reference to theDataSource
definition.
The code is as follows.
CLICK ME
What is transation ? source
A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the following four key properties described as ACID − Atomicity, Consistency, Isolation, Durability.
Step 8. Spring-web configuration, i.e. SpringMVC configuration
- 8.1: start
SpringMVC annotation
mvc:annotation-driven is used for enabling the Spring MVC components with its default configurations. If you dont include mvc:annotation-driven also your MVC application would work if you have used the context:component-scan for creating the beans or defined the beans in your XML file. But, mvc:annotation-driven does some extra job on configuring the special beans that would not have been configured if you are not using this element in your XML file.
- 8.2: specify the location of
static resources
, including .js, .gif, .png, .css,…
Steps to include static resources, e.g. css, js, into JSP page:
Put static resources like cs, js or images into this folder
webapp\resources
Create a
Spring mvc:resources
mappingInclude in JSP page via JSTL tag
c:url
or Spring tagspring:url
8.3: define
ViewResolver
When using JSP for a view technology you can use theUrlBasedViewResolver
. This view resolver translates a view name to a URL and hands the request over to theRequestDispatcher
to render the view.
- 8.4: define
multipartResolver
- 8.5: define
context:component-scan
The difference between <context:annotation-config />
and <context:component-scan />
Spring allows you to do two things: Autowiring of beans and Autodiscovery of beans
- Autowiring
Usually in applicationContext.xml you define beans and other beans are wired using constructor or setter methods. You can wire beans using XML or annotations. In case you use annotations, you need to activate annotations and you have to add<context:annotation-config />
in applicationContext.xml. This will simplify the structure of the tag from applicationContext.xml, because you will not have to manually wire beans (constructor or setter). You can use @Autowire annotation and the beans will be wired by type.
A step forward for escaping the manual XML configuration is
- Autodiscovery
Autodiscovery is simplifying the XML one step further, in the sense that you don’t even need too add the<bean>
tag in applicationContext.xml. You just mark the specific beans with one of the following annotation and Spring will automatically wire the marked beans and their dependencies into the Spring container. The annotations are as follow: @Controller, @Service, @Component, @Repository. By using<context:component-scan>
and pointing the base package, Spring will auto-discover and wire the components into Spring container.
As a conclusion:
<context:annotation-config />
is used in order to be able to use @Autowired annotation<context:component-scan />
is used to determine the search of specific beans and attempt of autowiring.
The code is as follows.
CLICK ME
Step 9. Edit web-xml file
Include listener, filter, mvc-dispatcher
CLICK ME To Show Code
index.jsp
index.html
spring-dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring/spring-*.xml
spring-dispatcher
/
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
CharacterEncodingFilter
/*