目录
环境说明:
数据库:MySQL 8.0
Java版本:JDK8
通过注解整合 SSM 框架流程:
- 创建 Web 工程
- SSM 整合
- Spring 框架:SpringConfig
- MyBatis 框架:JdbcConfig / jdbc.properties / MybatisConfig
- SpringMVC 框架:ServletConfig / SpringMvcConfig
一、创建Webapp项目
在 IDEA 中根据 “maven-archetype-webapp” 模板创建 Webapp 项目:
创建基本项目结构:
二、Spring配置类
引入 spring-conext 的依赖坐标:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.25.RELEASE</version>
</dependency>
创建一个 Java 类 SpringConfig
作为 Spring 配置类,类上面添加 @Configuration
注解标识这是一个配置类,添加 @ComponentScan
注解来设置扫描注解的路径
@Configuration
@ComponentScan("com.xxx")
/**
* 如果有多个要扫描的包路径,可以用数组格式:
* @ComponentScan({"com.xxx.dao","com.xxx.service"})
*/
public class SpringConfig {
}
三、数据源对象(以Druid为例)
导入 Druid 数据源的依赖坐标:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.22</version>
</dependency>
新建一个配置数据库连接信息的类 JdbcConfig
,里面引入配置文件中的数据库信息,然后用一个方法构造并返回一个 DataSource
对象,最后用 @Bean
注解设置这个方法的返回值成为 Spring IoC 容器的一个 Bean:
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 数据源Bean
* @return
*/
@Bean
public DataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
Spring 配置类 SpringConfig
中用 Import
注解引入 JdbcConfig
这个类:
@Configuration
@ComponentScan("com.xxx")
+@Import({JdbcConfig.class})
public class SpringConfig {
}
四、整合MyBatis
4.1、数据库配置
在 src/main/resources 目录下新建一个配置数据库连接信息的配置文件 jdbc.properties
:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db?useSSL=false&setUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
使用 @PropertySource
注解在 Spring 配置类 SpringConfig
上加载外部的 properties 文件:
@Configuration
@ComponentScan({"com.xxx"})
+@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}
4.2、MyBatis配置
导入 MyBatis 及 MySQL 的相关依赖坐标:
<!-- spring-jdbc -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.25.RELEASE</version>
</dependency>
<!-- mybatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.16</version>
</dependency>
<!-- mybatis-spring -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<!-- mysql -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
新建一个 MyBatis 的配置类 MybatisConfig
,配置 SqlSessionFactoryBean
和 MapperScannerConfigurer
这两个 Bean:
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setDataSource(dataSource);
ssfb.setTypeAliasesPackage("com.xxx.xxx");
return ssfb;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
// Mapper的XML映射文件所在路径
msc.setBasePackage("com.xxx.dao");
return msc;
}
}
Spring 配置类 SpringConfig
中用 Import
注解引入 MybatisConfig
这个类:
@Configuration
@ComponentScan("com.xxx")
+@Import({JdbcConfig.class, MybatisConfig.class})
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}
五、整合SpringMVC
导入 SpringMVC、Servlet 与 jackson 的依赖坐标:
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.25.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
</dependency>
新建 SpringMVC 配置类 SpringMvcConfig
:
@Configuration
@ComponentScan("com.wlplove.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
新建 Servlet 的初始化类 ServletInitializer
:
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
六、整合Log4j
导入 Log4j 的依赖坐标:
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.23.1</version>
</dependency>
在 "src/main/java/resources" 下新建一个 Log4j 的配置文件 Log4j2.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Configuration 具有 Appenders 和 Loggers 这两种子节点,每个子节点可以定义多个 -->
<configuration>
<!-- Appender节点,具有 Console(控制台)、File(文件)、RoolingFile(滚动文件)这三种类型的子节点 -->
<Appenders>
<!-- 输出日志信息到控制台 -->
<Console name="console" target="SYSTEM_OUT">
<!--指定控制日志输出的格式-->
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss SSS} [%t] %-3level %logger{1024} - %msg%n"/>
</Console>
<!-- File 节点用来定义输出到指定位置的文件的 Appender,会将所有内容写入到同一个文件中 -->
<!-- append属性设置写入新的日志时是追加在原内容后面,还是清除所有内容之后再写入 -->
<!-- <File name="allLog" fileName="logs/AlliInOne.log" append="true">-->
<!-- <ThresholdFilter level="ALL" onMatch="ACCEPT" onMismatch="DENY"/>-->
<!-- <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{9.9.9.1}(%L) %m%n"/>-->
<!-- </File>-->
<!-- RollingFile 节点,将日志写入文件,但是允许日志文件根据时间或大小进行滚动,从而避免单个文件过大 -->
<!-- fileName 生成的初始日志文件 -->
<RollingFile name="rollingFileInfo" fileName="logs/${date:yyyy-MM}/log-info-${date:yyyy-MM-dd}.log" filePattern="logs/${date:yyyy-MM}/log-info-%d{yyyy-MM-dd}-%i.log">
<!-- ThresholdFilter 只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
<ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
<!-- PatternLayout 指定控制日志输出的格式,不设置默认为:%m%n -->
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss SSS} [%t] %-3level %logger{1024} - %msg%n"/>
<!-- Policies 滚动策略 -->
<Policies>
<!-- 按时间滚动 -->
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<!-- 按大小滚动 -->
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy 设置一个文件下保存的日志文件数量,不设置则默认为同一文件夹下7个文件,超过这个数量后,最老的文件将被删除 -->
<DefaultRolloverStrategy max="20"/>
</RollingFile>
</Appenders>
<!-- 在 Loggers 中引入上面定义好的 Appender -->
<loggers>
<!-- level指定日志级别,从低到高的优先级:
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
-->
<!-- 设置org.mybatis包下的日志只打印WARN及以上级别 -->
<Logger name="org.mybatis" level="WARN" additivity="false">
<appender-ref ref="console"/>
<appender-ref ref="rollingFileInfo"/>
</Logger>
<!-- 设置org.springframework包下的日志只打印WARN及以上级别 -->
<Logger name="org.springframework" level="WARN" additivity="false">
<appender-ref ref="console"/>
<appender-ref ref="rollingFileInfo"/>
</Logger>
<root level="DEBUG">
<appender-ref ref="console"/>
<appender-ref ref="rollingFileInfo"/>
</root>
</loggers>
</configuration>
Log4j 配置文件详解:彻底掌握Log4j2 - 蚂蚁小哥 - 博客园
修改 MyBatis 配置类中的 SqlSessionFactoryBean
,设置其 Configuration
属性:
public class MybatisConfig {
// ...
@Bean
public SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.xxx.xxx");
ssfb.setDataSource(dataSource);
+ Configuration configuration = new Configuration();
+ // 修改MyBatis使用的日志框架为Log4j
+ configuration.setLogImpl(Log4j2Impl.class);
+ ssfb.setConfiguration(configuration);
return ssfb;
}
// ...
}
七、整合Junit
导入 Junit 和 Spring-test 的依赖坐标:
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
新建一个测试类:
// 在 JUnit 5 中集成 Spring 功能(如果是Junit4则换成@RunWith(SpringJunit4ClassRunner.class))
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SpringConfig.class)
public class SpringTest {
@Autowired
private UserMapper userMapper;
@Test
public void find() {
User user = userMapper.select();
}
}
评论 (0)