Spring
简介
- spring是轻量级、非入侵式的框架
- 控制反转(IOC) 面向切面编程(AOP)
- 支持事务的处理、对框架整合的支持
Spring就是轻量级的控制反转(IOC) 面向切面编程(AOP)的框架
Maven包
<dependencies>
<dependency>
<!-- spring-->
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!-- spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!-- mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- aop-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
IOC
IOC理论
控制反转
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI)
控制:传统应用的对象又程序本身控制,使用spring后 对象由Spring控制
反转:程序本身不创建对象,而变成被动的接收对象
依赖注入:利用set方法来为对象注入
ioc是一种编程思想,由主动编程变成被动的接收
IOC是spring的核心内容
<?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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
</beans>
Ioc创建流程
配置 beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mysql" class="com.jie.dao.UserMysqlImpl"/>
<bean id="userDao" class="com.jie.dao.UserDaoImpl"/>
<bean id="userService" class="com.jie.service.UserServiceImpl">
<!-- ref 引用Spring中创建好的对象-->
<property name="userDao" ref="mysql"/>
</bean>
</beans>
获取spring的容器 由spring来实例对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl service = (UserServiceImpl)context.getBean("userService");
service.getUser();
IOC设置
创建对象
ioc默认调用无参构造 并使用set方法传值
若无无参构造 则有以下方法
-
下标传值
<bean id="zcj" class="com.jie.pojo.User"> <constructor-arg index="0" value="zcj"/> </bean>
-
直接通过参数名 (推荐)
<bean id="zcj" class="com.jie.pojo.User">
<constructor-arg name="name" value="zcj2"/>
</bean>
配置
别名
别名与本身的名字都可以使用
<alias name="zcj" alias="user"/>
- 在name中设置别名(可以使用, 空格 ; 分割)
<bean id="zcj" class="com.jie.pojo.User" name="zcj1,zcj2,zcj3">
<constructor-arg name="name" value="zcj2"/>
</bean>
import导入bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
</beans>
依赖注入
构造器注入
set注入
-
依赖注入:set注入
- 依赖:bean对象的创建全部依赖容器
- 注入:bean对象的所有属性,由容器来创建
-
方式
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="add" class="com.jie.pojo.Address"> <property name="address" value="芜湖"/> </bean> <bean id="student" class="com.jie.pojo.Student"> <!-- 第一种 value注入 --> <property name="name" value="周成杰"/> <!-- 第二种 bean注入--> <property name="address" ref="add"/> <!-- 数组注入--> <property name="books"> <array> <value>java入门</value> <value>c++入门</value> <value>c#入门</value> <value>python入门</value> </array> </property> <!-- list注入--> <property name="hobbies"> <list> <value>打游戏</value> <value>看电影</value> </list> </property> <!-- map注入--> <property name="card"> <map> <entry key="身份证" value="123456"/> <entry key="银行卡" value="123123213123"/> </map> </property> <!-- set注入--> <property name="games"> <set> <value>lol</value> <value>cf</value> <value>dnf</value> </set> </property> <property name="WIFI"> <null/> </property> <property name="info"> <props> <prop key="username">admin</prop> <prop key="password">123456</prop> </props> </property> </bean> </beans>
扩展方式注入
p命名空间注入 (利用无参构造)
引入约束标签
xmlns:p="http://www.springframework.org/schema/p"
配置
<!-- p命名空间注入-->
<bean id="user" class="com.jie.pojo.User" p:name="zcj" p:age="18"/>
c命名空间注入 (利用有参构造)
xmlns:c="http://www.springframework.org/schema/c"
<!-- c命名空间注入 通过构造器注入-->
<bean id="user2" class="com.jie.pojo.User" c:name="zcj2" c:age="21"/>
bean作用域
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1WJlLAVX-1603806682372)(D:\study\img\3.png)]
1、单例模式(spring默认就是单例模式)
<bean id="user2" class="com.jie.pojo.User" c:name="zcj2" c:age="21" scope="singleton"/>
2.原型模式
从容器中获取的为创建的新对象
<bean id="user2" class="com.jie.pojo.User" c:name="zcj2" c:age="21" scope="prototype"/>
3.其余的只能在wep中使用
Bean自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找,并给bean装配属性
spring中的三种装配方式
- 在xml中显示的配置
- 在java中显示配置
- 隐式的自动装配bean**【重点】**
1.byname自动装配
根据set方法后面的名字自动装配,若名字不相同则装配不成功
<bean name="people" class="com.jie.pojo.People" autowire="byName">
<property name="name" value="zcj"/>
</bean>
2.byType自动装配
根据数据类型装配 但容器里的匹配class为唯一 否则报错
<bean name="people" class="com.jie.pojo.People" autowire="byType">
<property name="name" value="zcj"/>
</bean>
注解自动装配
需要:
导入约束
xmlns:context="http://www.springframework.org/schema/context"
~~~~
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
导入注解的支持
<context:annotation-config/>
如下:
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
@Autowired
直接在属性上使用 或者在set方法使用
在ioc容器中寻找类的 类型 进行装配 (byType的方式)
@Autowired
@Qualifier(value = "dog123")
private Dog dog;
添加注解 @Qualifier(value = “dog123”) 可以指定名字对应的类进行装配
@Resource
默认与类型匹配 括号可以设置名字(“java原生态注解”)
@Resource
private Cat cat;
@Resource(name = "dog123")
private Dog dog;
总结:
@Autowired 默认按type注入
**@Qualifier(“cusInfoService”) ** 一般作为@Autowired()的修饰用
@Resource(name=“cusInfoService”) 默认按name注入,可以通过name和type属性进行选择性注入
注解开发
IOC容器
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.jie"/>
</beans>
属性注入
导入范围包
<context:component-scan base-package="com.jie"/>
@Component
放在类上 默认为放在IOC容器中 名字为首字母小写
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
public String name;
}
@Value
默认set值
public class User {
@Value("zcj")
public String name;
}
@Component衍生注解
与Component相同 代表MVC三层架构不同的位置注解
dao:@Repository
service:@Service
controller: @Controller
功能相同
自动装配
@Autowired
默认按type注入
@Qualifier
**@Qualifier(“cusInfoService”) ** 一般作为@Autowired()的修饰用
@Resource
@Data
@AllArgsConstructor
@NoArgsConstructor
public class People {
@Resource
private Cat cat;
@Resource()
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Resource(name=“cusInfoService”) 默认按name注入,可以通过name和type属性进行选择性注入
作用域
@Scope
原型模式
@Scope("prototype")
public class User {
@Value("zcj")
public String name;
}
单例模式
@Scope("singleton")
public class User {
@Value("zcj")
public String name;
}
总结:
XML万能 适合各种场景
注解轻巧 维护相对复杂
最佳:
XML负责管理bean
注解只负责属性的注入
Java配置Spring(appConfig)
@Configuration
加上**@Configuration**注解后 这个类就会变为原来的IOC容器池 添加bean
能使用xml配置的任何功能
实体类
@ComponentScan
扫描文件夹
配置文件
@Configuration
@ComponentScan("com.jie.pojo")
@Import(jieConfig2.class)
public class jieConfig {
@Bean
@Scope("prototype")
public User getUser(){
System.out.println("123321");
return new User();
}
}
@Bean
在方法上加入**@Bean** 即为xml中的 注入
测试类
public class test1 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(jieConfig.class);
User user = context.getBean("getUser", User.class);
User user2 = context.getBean("user", User.class);
System.out.println(user+" "+user2);
}
}
若用appconfig配置 需要使用类
new AnnotationConfigApplicationContext(jieConfig.class) 读取
代理模式
代理模式
代理模式是AOP的底层
分为:静态代理和动态代理
静态代理
抽象角色: 使用抽象类和接口来解决
public interface Rent {
void rent();
}
真实角色:被代理的角色
public class Host implements Rent {
public void rent() {
System.out.println("租房");
}
}
代理角色:代理真实角色,做真实角色的事后 可以做一下附属操作
public class Proxy implements Rent {
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
public void rent() {
say();
host.rent();
send();
}
public void send(){
System.out.println("中介收费");
}
public void say(){
System.out.println("中介找人");
}
}
客户:访问代理客户的人
public class Client {
public static void main(String[] args) {
Host host=new Host();
host.rent();
Proxy proxy=new Proxy(host);
proxy.rent();
}
}
优点:
- 可以使真实角色的操作更加纯粹,不用关注公共业务
- 公共交给了代理 实现了业务的分工
- 公共方法发展扩展的时候 方便管理
缺点:
- 一个真实角色代表一个代理角色 多个角色效率会便低 (使用动态代理解决)
动态代理
- 动态代理和静态代理相同
- 动态代理的代理类是动态生成的,不是直接写死的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口:jdk动态代理
- 基于类:cglib
- java字节码实现:javasist
jdk动态代理
实现InvocationHandler接口
使用Proxy对象 提供创建动态代理类和实例的静态方法
模板
package com.jie.demo04;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成代理对象
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
//处理代理实例
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.toString());
Object result=method.invoke(target,args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg);
}
}
实例使用
public class Client {
public static void main(String[] args) {
//真实角色
Host host=new Host();
//设置代理
ProxyInvocationHandler p= new ProxyInvocationHandler();
p.setTarget(host);
//获得代理角色
Rent rent= (Rent) p.getProxy();
//执行
rent.rent();
}
}
AOP
AOP(Aspect Oriented Programming)意为∶面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
Aop在Spring中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
- 切面(ASPECT)︰横切关注点被模块化的特殊对象。即,它是一个类。
- 通知(Advice) :切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target)︰被通知对象。
- 代理(Proxy)︰向目标对象应用通知之后创建的对象。
- 切入点(PointCut) ︰切面通知执行的“地点"的定义。
- 连接点(JointPoint) :与切入点匹配的执行点。
使用springAPI接口
设置前置日志
//spring的代理方法
public class Log implements MethodBeforeAdvice {
//method: 要执行的目标对象的方法
//arg 参数
//target:目标对象
public void before(Method method, Object[] arg, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
后置日志
public class AfterLog implements AfterReturningAdvice {
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+" 返回结果为:"+o);
}
}
配置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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean-->
<bean id="userService" class="com.jie.service.UserServiceImpl"/>
<bean id="log" class="com.jie.log.Log"/>
<bean id="afterLog" class="com.jie.log.AfterLog"/>
<!-- 配置aop-->
<!-- //方式1-->
<aop:config>
<!-- 切除点-->
<aop:pointcut id="pointcut" expression="execution(* com.jie.service.UserServiceImpl.*(..))"/>
<!-- 执行环绕-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试
public class Test1 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//代理是个接口
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
使用自定义类
设置自定义类
public class DiyProxy {
public void before(){
System.out.println("before");
}
public void after(){
System.out.println("after");
}
}
在xml中设置切面
<!-- 方式2-->
<bean id="diy" class="com.jie.div.DiyProxy"/>
<aop:config>
<!-- 自定义切面-->
<aop:aspect ref="diy">
<!-- 切入点-->
<aop:pointcut id="point" expression="execution(* com.jie.service.UserServiceImpl.*(..))"/>
<!-- 通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
测试
public class Test2 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//代理是个接口
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
使用注解配置
//标注为切面
@Aspect
public class AnnotationPoint {
@Before("execution(* com.jie.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("before");
}
@After("execution(* com.jie.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("after");
}
}
xml中配
<!-- 方式3-->
<bean id="annotationPoint" class="com.jie.div.AnnotationPoint"/>
<!-- 开启注解支持-->
<aop:aspectj-autoproxy/>
mybaits回顾
核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.jie.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<!-- 事务管理器-->
<transactionManager type="JDBC"/>
<!-- 数据源-->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username=root
password=123456
sqlsession工厂
package com.jie.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource="mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
mybaits-spring
流程
1.编写数据源
<!-- DateSource 使用spring 代替mybatis的配置-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
2.sqlSessionFactory
<!-- sqlSessionFactory-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!-- 绑定mybatis-->
<property name="configLocation" value="mybatis-config.xml"/>
<property name="mapperLocations" value="UserMapper.xml"/>
</bean>
3.SqlSessionTemplate
<!-- SqlSessionTemplate是需要使用sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sessionFactory"/>
</bean>
4.为接口设置实现类
public interface UserMapper {
List<User> selectUser();
}
5.实现类注入
<bean id="userMapper" class="com.jie.mapper.UerMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
总结
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.jie.pojo"/>
</typeAliases>
</configuration>
接口
package com.jie.mapper;
import com.jie.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> selectUser();
User select(String u);
}
实现类
package com.jie.mapper;
import com.jie.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UerMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
public User select(String u) {
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
return mapper.select(u);
}
}
userMapper.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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.jie.mapper.UserMapper">
<!--select查询语句-->
<select id="selectUser" resultType="user">
select * from web.user;
</select>
</mapper>
applicationontext.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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-mapper.xml"/>
<bean id="userMapper" class="com.jie.mapper.UerMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
spring-mapper.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- DateSource 使用spring 代替mybatis的配置-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- sqlSessionFactory-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!-- 绑定mybatis-->
<property name="configLocation" value="mybatis-config.xml"/>
<property name="mapperLocations" value="UserMapper.xml"/>
</bean>
<!-- SqlSessionTemplate是需要使用sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sessionFactory"/>
</bean>
</beans>
测试类
@Test
public void select(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper mapper = context.getBean("userMapper", UserMapper.class);
List<User> userList = mapper.selectUser();
for (User user:userList){
System.out.println(user);
}
User admin = mapper.select("admin");
System.out.println(admin);
}
方法2:SqlSessionDaoSupport
mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.jie.pojo"/>
</typeAliases>
</configuration>
接口
public interface UserMapper {
List<User> selectUser();
User select(String u);
}
实现类
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
public User select(String u) {
SqlSession sqlSession=getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.select(u);
}
}
UserMapper.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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.jie.mapper.UserMapper">
<!--select查询语句-->
<select id="selectUser" resultType="user">
select * from web.user;
</select>
<select id="select" resultType="user">
select * from web.user where user=#{u};
</select>
</mapper>
bean配置文件
<?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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-mapper.xml"/>
<bean id="userMapper2" class="com.jie.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sessionFactory"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- DateSource 使用spring 代替mybatis的配置-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- sqlSessionFactory-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!-- 绑定mybatis-->
<property name="configLocation" value="mybatis-config.xml"/>
<property name="mapperLocations" value="UserMapper.xml"/>
</bean>
</beans>
测试类
@Test
public void select2(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper mapper = context.getBean("userMapper2", UserMapper.class);
List<User> userList = mapper.selectUser();
for (User user:userList){
System.out.println(user);
}
User admin = mapper.select("admin");
System.out.println(admin);
}
声明式事务
事务:要么成功,要么失败
ACID原则:
- 原子性
- 一致性
- 隔离性
- 持久性
在spring-mapper.xml中配置
<!-- 配置声明事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入-->
<aop:config>
<aop:pointcut id="txPoint" expression="execution(* com.jie.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
开启事务