目录
- 1.SSM介绍
-
- [1.1 什么是SSM?](#1.1 什么是SSM?)
- [1.2 SSM框架](#1.2 SSM框架)
-
- [1.2.1 Spring](#1.2.1 Spring)
- [1.2.2 SpringMVC](#1.2.2 SpringMVC)
- [1.2.3 MyBatis](#1.2.3 MyBatis)
- 2.SSM框架整合
-
- [2.1 建库建表](#2.1 建库建表)
- [2.2 创建工程](#2.2 创建工程)
- [2.3 pom.xml](#2.3 pom.xml)
- [2.4 log4j.properties](#2.4 log4j.properties)
- [2.5 db.properties](#2.5 db.properties)
- [2.6 applicationContext-dao.xml](#2.6 applicationContext-dao.xml)
- 2.7.applicationContext-tx.xml
- [2.8 applicationContext-service.xml](#2.8 applicationContext-service.xml)
- [2.9 springmvc.xml](#2.9 springmvc.xml)
- [2.10 web.xml](#2.10 web.xml)
- [2.11 pojo](#2.11 pojo)
- [2.12 mapper](#2.12 mapper)
- [2.13 service](#2.13 service)
- [2.14 controller](#2.14 controller)
- [2.15 jsp](#2.15 jsp)
- [2.16 测试](#2.16 测试)
- [2.17 项目目录结构](#2.17 项目目录结构)
- 3.待改造的问题
-
- [3.1 jdbc配置](#3.1 jdbc配置)
- [3.2 mybatis配置](#3.2 mybatis配置)
- [3.3 transactional配置](#3.3 transactional配置)
- [3.4 service配置](#3.4 service配置)
- [3.5 springmvc配置](#3.5 springmvc配置)
- [3.6 servlet配置](#3.6 servlet配置)
- 4.相关注解说明
-
- [4.1 相关注解和xml对应关系](#4.1 相关注解和xml对应关系)
- [4.2 @Configuration](#4.2 @Configuration)
- [4.3 @ComponentScan](#4.3 @ComponentScan)
- [4.4 @Bean](#4.4 @Bean)
- [4.5 @PropertySource](#4.5 @PropertySource)
- [4.6 @Import](#4.6 @Import)
- 5.Spring的纯注解配置
-
- [5.1 JdbcConfig](#5.1 JdbcConfig)
- [5.2 MybatisConfig](#5.2 MybatisConfig)
- [5.3 TxConfig](#5.3 TxConfig)
- [5.4 SpringConfig](#5.4 SpringConfig)
- [5.5 SpringMvcConfig](#5.5 SpringMvcConfig)
- [5.6 WebConfig](#5.6 WebConfig)
- [5.7 删除xml配置文件](#5.7 删除xml配置文件)
- [5.8 修改web.xml](#5.8 修改web.xml)
- [5.9 测试](#5.9 测试)
1.SSM介绍
1.1 什么是SSM?
SSM全称Spring+SpringMVC+MyBatis,是spring、spring MVC 、和mybatis框架的整合,为标准的MVC模式,是目前比较主流的Java EE企业级框架,适用于搭建各种大型的企业级应用系统。
-
使用Spring实现业务对象的管理;
-
使用SpringMVC负责请求的转发和视图的管理;
-
使用MyBatis作为数据对象的持久化引擎。
标准的SSM框架有四层,分别是dao(mapper)
层,service
层,controller
层和View
层。使用spring实现业务对象管理,使用spring MVC负责请求的转发和视图管理,mybatis作为数据对象的持久化引擎。
1.2 SSM框架
1.2.1 Spring
Spring是一个开源的控制反转(IoC)和面向切面(AOP)的容器框架,用来简化企业开发。
- IOC(控制反转)
是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度,最常见的方式叫做依赖注入(Dependency Injection,简称DI),通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。
- AOP(面向切面编程)
AOP使业务逻辑各部分间的耦合度降低,提高程序可重用性,提高开发效率。
详细参考:Spring IoC详解,Spring AOP详解
1.2.2 SpringMVC
Spring MVC 分离了 控制器、模型 对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
SpringMVC的优点:
-
springMVC是使用了MVC设计思想的轻量级web框架,对web层进行解耦,是的我们开发更简洁。
-
与Spring无缝衔接。
-
灵活的数据验证,格式化,数据绑定机制。
详细参考:Spring MVC详解,Spring MVC拦截器、文件上传和全局异常处理
1.2.3 MyBatis
MyBatis是一种开源的持久化框架,它通过XML或注解配置SQL映射,将Java对象映射到关系型数据库中的表。MyBatis可以将数据查询结果映射成Java对象,也可以将Java对象插入、更新、删除到数据库中。
MyBatis的核心组件包括:
-
SqlSessionFactory:创建SqlSession的工厂类,用于生成SqlSession对象。
-
SqlSession:MyBatis与数据库交互的会话,可以使用SqlSession执行数据库操作,例如查询、更新、删除、插入等。
-
Mapper:Mapper是Java接口,用于定义数据库操作方法。Mapper接口中的方法名和参数类型与Mapper.xml文件中的SQL语句绑定。
-
Mapper.xml:Mapper.xml文件用于定义SQL语句,包括查询、更新、删除、插入等操作,也可以进行参数的动态组装。
详细参考:MyBatis详解
2.SSM框架整合
2.1 建库建表
sql
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.2 创建工程
2.3 pom.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.by</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>5.2.8.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.47</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
<druid.version>1.1.0</druid.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</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>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!--端口号-->
<port>8080</port>
<!--项目名-->
<path>/</path>
<!--按UTF-8进行编码-->
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
2.4 log4j.properties
properties
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} - %c%l%m%n
2.5 db.properties
properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1111
2.6 applicationContext-dao.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
</bean>
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 别名-->
<property name="typeAliasesPackage" value="com.by.pojo"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.by.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
2.7.applicationContext-tx.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.by.service.*.*(..))" />
</aop:config>
</beans>
2.8 applicationContext-service.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 扫描service的包 -->
<context:component-scan base-package="com.by.service"></context:component-scan>
</beans>
2.9 springmvc.xml
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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">
<!-- 配置创建 spring 容器要扫描的包 -->
<context:component-scan base-package="com.by.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
2.10 web.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置Spring的监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 解决post乱码 -->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- springmvc的前端控制器 -->
<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.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 拦截/,例如:/user/add -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.11 pojo
java
public class Account {
private Integer id;
private String name;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
2.12 mapper
java
public interface AccountMapper {
List<Account> selectAccount();
}
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.mapper.AccountMapper">
<select id="selectAccount" resultType="Account">
select * from account
</select>
</mapper>
2.13 service
java
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public List<Account> selectAccount() {
return accountMapper.selectAccount();
}
}
2.14 controller
java
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/selectAccount")
public String selectAccount(Model model){
List<Account> list = accountService.selectAccount();
model.addAttribute("list",list);
return "select_account";
}
}
2.15 jsp
html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>查询所有账户</h2>
<table width="30%" border="1" cellspacing="0" cellpadding="0">
<tr>
<th>id</th>
<th>name</th>
<th>money</th>
</tr>
<c:forEach var="list" items="${list}">
<tr>
<td>${list.id}</td>
<td>${list.name}</td>
<td>${list.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
2.16 测试
2.17 项目目录结构
3.待改造的问题
我们发现,之所以我们现在离不开xml配置文件,是因为我们有一处很关键的配置,如果他要也能用注解配置,那么我们就可以脱离xml文件了:
3.1 jdbc配置
xml
<context:property-placeholder location="classpath:db.properties">
</context:property-placeholder>
<!--数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
</bean>
3.2 mybatis配置
xml
<!--sqlSession工厂-->
<bean id="sessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.by.pojo"></property>
</bean>
<!--配置MapperScan扫描mapper接口,并把生成的代理类交给spring去管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.by.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sessionFactoryBean"></property>
</bean>
3.3 transactional配置
xml
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启spring对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
3.4 service配置
xml
<!--扫描service-->
<context:component-scan base-package="com.by.service"></context:component-scan>
3.5 springmvc配置
xml
<!--配置springmvc要扫描的包-->
<context:component-scan base-package="com.by.controller,com.by.exception"></context:component-scan>
<!--开启注解驱动:配置handlerMapping和handlerAdapter-->
<mvc:annotation-driven conversion-service="cs"></mvc:annotation-driven>
<!--配置日期转换器-->
<bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.by.converter.MyDateConverter"></bean>
</set>
</property>
</bean>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置文件上传解析器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!--资源映射器:直接放行无须dispatcherServlet去处理-->
<mvc:resources location="/head/" mapping="/head/**"/>
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/account/**"/>
<mvc:exclude-mapping path="/account/login"></mvc:exclude-mapping>
<bean class="com.by.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
3.6 servlet配置
xml
<!--配置监听器:监听tomcat启动,加载spring配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!--前端控制器-->
<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.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4.相关注解说明
4.1 相关注解和xml对应关系
注解 | 位置 | 对应的XML标签 | 作用 |
---|---|---|---|
@Configuration | 类 | 声明当前类为配置类,相当于xml形式的Spring配置 | |
@ComponentScan | 类 | <context:component-scan> |
用于对Component进行扫描 |
@Bean | 方法 | <bean> |
声明当前方法的返回值为一个bean |
@PropertySource | 类 | <context:property-placeholder> |
用于加载*.properties文件中的配置 |
@Import | 类 | <import> |
用来导入配置类或者一些需要前置加载的类 |
4.2 @Configuration
-
作用:用于指定当前类是一个spring配置类,可替换web.xml配置文件
-
示例:
java/** * spring的配置类 */ @Configuration public class SpringConfiguration{ }
4.3 @ComponentScan
-
作用:
用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件中的:
<context:component-scan base-package="com.by"/>
是一样的。 -
属性:
- basePackages:用于指定要扫描的包。和该注解中的value属性作用一样。
-
示例代码
java/** * spring的配置类 */ @Configuration @ComponentScan(basePackages = "com.by")//等价于<context:component-scan> public class SpringConfiguration{ }
4.4 @Bean
-
作用:
该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器。作用和在spring的xml配置文件中的:
<bean/>
是一样的。 -
属性:
- name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)。
-
示例代码
javapublic class Dog { private String nam; private Integer age; //set get...... }
java@Bean public Dog dog(){ Dog dog = new Dog(); dog.setNam("二狗"); dog.setAge(18); return dog; }
4.5 @PropertySource
-
作用:
用于加载*.properties文件中的配置。作用和在spring的xml配置文件中的:
<context:property-placeholder location="">
是一样的。 -
属性:
- value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath:
-
示例代码
properties#config.properties nam=二狗 age=18
java@PropertySource("classpath:config.properties") public class SpringConfiguration { @Value("${nam}") private String nam; @Value("${age}") private Integer age; @Bean public Dog dog(){ Dog dog = new Dog(); dog.setNam(nam); dog.setAge(age); return dog; } }
4.6 @Import
-
作用:
@Import注解是用来导入配置类或者一些需要前置加载的类。作用和在spring的xml配置文件中的:
<import resource=""></import>
是一样. -
属性:
- value[]:用于指定其他配置类的字节码。
-
示例代码
java@Configuration @ComponentScan(basePackages = "com.by") @Import({Configuration_Other.class}) public class SpringConfiguration { } @PropertySource("classpath:config.properties") public class Configuration_Other { }
5.Spring的纯注解配置
5.1 JdbcConfig
java
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@PropertySource("classpath:db.properties")
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("dataSource")
public DataSource getDatasource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
5.2 MybatisConfig
java
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(
DataSource dataSource){
SqlSessionFactoryBean ssfb=new SqlSessionFactoryBean();
ssfb.setDataSource(dataSource);
ssfb.setTypeAliasesPackage("com.by.pojo");
return ssfb;
}
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer msc=new MapperScannerConfigurer();
msc.setBasePackage("com.by.mapper");
return msc;
}
}
5.3 TxConfig
java
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
public class TxConfig {
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}
5.4 SpringConfig
java
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@Import({MyBatisConfig.class, JdbcConfig.class, TxConfig.class})
//等同<context:component-scan base-package="com.by"/>`
@ComponentScan(value = "com.by.service")
//等同于<tx:annotation-driven />,bean的名称默认取transactionManager
@EnableTransactionManagement
public class SpringConfig {
}
5.5 SpringMvcConfig
java
import com.by.converter.MyDateConverter;
import com.by.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
//等同于<context:component-scan base-package="com.by.controller>
@ComponentScan("com.by.controller")
//等同于<mvc:annotation-driven></mvc:annotation-driven>
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/"); // 设置视图文件所在目录
viewResolver.setSuffix(".jsp"); // 设置视图文件后缀名
return viewResolver;
}
@Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setMaxInMemorySize(5242880);
commonsMultipartResolver.setDefaultEncoding("utf-8");
return commonsMultipartResolver;
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new MyDateConverter());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/head/**").addResourceLocations("/head/");
}
}
5.6 WebConfig
java
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
/**
* 当类扩展了AbstractAnnotationConfigDispatcherServletlnitializer并将其部署到 Servlet容器时,
* 容器会自动发现它,并用它来配置Servlet环境
*/
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
//加载Spring配置类
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
//加载SpringMVC配置类
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
//设置SpringMVC请求地址拦截规则
protected String[] getServletMappings() {
return new String[]{"/"};
}
//设置post请求中文乱码过滤器
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("utf-8");
return new Filter[]{filter};
}
}
5.7 删除xml配置文件
5.8 修改web.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>