? 理念: 使现有的技术更加实用,本事就是一个大杂烩,整合现有的框架技术。
……
Spring是一个轻量级的控制反转(IOC)和面向切面(Aop)编程的容器(框架)。

核心容器(Spring Core)
核心容器提供Spring框架的基本功能。Spring以bean的方式组织和管理Java应用中的各个组件及其关系。Spring使用BeanFactory来产生和管理Bean,它是工厂模式的实现。BeanFactory使用控制反转(IoC)模式将应用的配置和依赖性规范与实际的应用程序代码分开。
应用上下文(Spring Context)
Spring上下文是一个配置文件,向Spring框架提供上下文信息。Spring上下文包括企业服务,如JNDI、EJB、电子邮件、国际化、校验和调度功能。
Spring面向切面编程(Spring AOP)
通过配置管理特性,Spring AOP 模块直接将面向方面的编程功能集成到了 Spring框架中。所以,可以很容易地使 Spring框架管理的任何对象支持 AOP。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖 EJB 组件,就可以将声明性事务管理集成到应用程序中。
JDBC和DAO模块(Spring DAO)
JDBC、DAO的抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理,和不同数据库供应商所抛出的错误信息。异常层次结构简化了错误处理,并且极大的降低了需要编写的代码数量,比如打开和关闭链接。
对象实体映射(Spring ORM)
Spring框架插入了若干个ORM框架,从而提供了ORM对象的关系工具,其中包括了Hibernate、JDO和 IBatis SQL Map等,所有这些都遵从Spring的通用事物和DAO异常层次结构。
Web模块(Spring Web)
Web上下文模块建立在应用程序上下文模块之上,为基于web的应用程序提供了上下文。所以Spring框架支持与Struts集成,web模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
MVC模块(Spring Web MVC)
MVC框架是一个全功能的构建Web应用程序的MVC实现。通过策略接口,MVC框架变成为高度可配置的。MVC容纳了大量视图技术,其中包括JSP、POI等,模型来有JavaBean来构成,存放于m当中,而视图是一个街口,负责实现模型,控制器表示逻辑代码,由c的事情。Spring框架的功能可以用在任何J2EE服务器当中,大多数功能也适用于不受管理的环境。Spring的核心要点就是支持不绑定到特定J2EE服务的可重用业务和数据的访问的对象,毫无疑问这样的对象可以在不同的J2EE环境,独立应用程序和测试环境之间重用。
在之前的代码,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
我们可以使用set接口实现,已经发生了革命性的变化
private UserDao userDao;
//利用set进行动态实现值得注入!
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
这种思想,从本质上解决了问题,程序员不用再去管理对象的创建了。系统的耦合性大大降低了,可以更加专注的在业务的实现上!这是IOC的原型!
控制反转(IOC):是一种设计思想,DI(依赖注入)是实现IOC的一种方法。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IOC容器,其实现方法是依赖注入(Dependency Injection,DI)
package com.king.pojo;
/**
*/
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str=‘" + str + ‘\‘‘ +
‘}‘;
}
}
类型 变量名 = new 类型();
Hello hello = new Hello();
id = 变量名
class = new 的对象
property 相当于给对象中的属性设置一个值!
<?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">
<!-- ApplicationContext.xml配置文件 -->
<bean id="hello" class="com.king.pojo.Hello">
<property name="str" value="HelloSpring"/>
</bean>
</beans>
测试类
import com.king.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//我们的对象现在都在Spring中管理了,我们要是使用,直接去里面取出来就可以!
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello);
}
}
到此为止,切蒂不用再去程序中改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,一句话:对象由Spring来创建,管理,装配!
<!-- ApplicationContext.xml 的bean中的property标签的属性 -->
ref:引用Spring容器中创建好的对象
value: 具体的值,基本数据类型!
使用无参构造对象,默认~
假设我们要使用有参构造创建对象。
下标赋值
<bean id="user" class="com.king.pojo.User">
<constructor-arg index="0" value="king"/>
</bean>
通过类型创建:不建议使用
通过参数名
<bean id="user" class="com.king.pojo.User">
<constructor-arg name="name" value="king"/>
</bean>
总结:在配置文件夹在的时候,容器中管理的对象就已经初始化了!
<alias name="user" alias="user2"/>
<!--
id: Bean的唯一标识符,也就是相当于我们的对象名
class: bean 对象所对应的全限定名: 包名 + 类型
name: 也是别名
-->
<bean id="user" class="com.king.pojo.User" name="user2"/>
import,一般用于团队开发使用,它可以将多个配置文件,导入合并为一个
<import resource="beans.xml"/>
讲过了!
【环境搭建】
package com.king.pojo;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address=‘" + address + ‘\‘‘ +
‘}‘;
}
}
package com.king.pojo;
import java.util.*;
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> game;
private String wife;
private Properties info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List<String> getHobbys() {
return hobbys;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGame() {
return game;
}
public void setGame(Set<String> game) {
this.game = game;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name=‘" + name + ‘\‘‘ +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbys=" + hobbys +
", card=" + card +
", game=" + game +
", wife=‘" + wife + ‘\‘‘ +
", info=" + info +
‘}‘;
}
}
测试类:
import com.king.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.king.pojo.Address"/>
<bean id="student" class="com.king.pojo.Student">
<!-- 普通注入 value-->
<property name="name" value="king"/>
<!-- bean 注入 ref -->
<property name="address" ref="address"/>
<!-- 数组注入 -->
<property name="books">
<array>
<value>红楼梦</value>
<value>三国演义</value>
<value>西游记</value>
<value>水浒传</value>
</array>
</property>
<!-- List 注入 -->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property>
<!-- map注入-->
<property name="card">
<map>
<entry key="身份证" value="11111111111111122222222222222"/>
<entry key="银行卡" value="111111111111111113333333332124"/>
</map>
</property>
<!-- set注入-->
<property name="game">
<set>
<value>LOL</value>
<value>CSGO</value>
<value>DNF</value>
</set>
</property>
<!-- null值注入-->
<property name="wife">
<null/>
</property>
<!-- properties注入-->
<property name="info">
<props>
<prop key="id">20182018</prop>
<prop key="name">king</prop>
<prop key="sex">男</prop>
</props>
</property>
</bean>
</beans>
结果:
Student{
name=‘king‘,
address=Address{address=‘四川‘},
books=[红楼梦, 三国演义, 西游记, 水浒传],
hobbys=[听歌, 敲代码, 看电影],
card={身份证=11111111111111122222222222222, 银行卡=111111111111111113333333332124},
game=[LOL, CSGO, DNF],
wife=‘null‘,
info={sex=男, name=king, id=20182018}
}
P命名空间和C命名空间


单例模式(Spring的默认机制)
<bean id="user" class="com.king.pojo.User" c:age="18" c:name="king" scope="singleton"/>
原型模式:每次从容器中get的时候,都会产生一个新对象!
<bean id="user" class="com.king.pojo.User" c:age="18" c:name="king" scope="prototype"/>
在Spring中有三种装配的方式
环境搭建:一个人两个宠物
<bean id="cat" class="com.king.pojo.Cat"/>
<bean id="dog" class="com.king.pojo.Dog"/>
<!--
byName: 会自动在容器上下文中查找,和自己对象set方法后面的值对应的 beanid
-->
<bean id="people" class="com.king.pojo.People" autowire="byName">
<property name="name" value="king"/>
</bean>
<bean id="cat" class="com.king.pojo.Cat"/>
<bean id="dog" class="com.king.pojo.Dog"/>
<!--
byType: 会自动在容器上下文中查找,和自己对象属性类型相同的bean !
-->
<bean id="people" class="com.king.pojo.People" autowire="byType">
<property name="name" value="king"/>
</bean>
小结:
jdk1.5支持的注解,Spring2.5就支持注解了!
要使用注解须知:
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null;
public @interface Autowired {
boolean required() default true;
}
测试代码:
public class People {
//如果显示定义了Autowired的required属性为false,则说明这个属性可以为空,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value="xxx")去配合@Autowired的使用,指定一个唯一的bean对象注入!
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog222")
private Dog dog;
private String name;
public class User {
//如果允许对象为null,设置required = false,默认为true
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String str;
}
<bean id="dog" class="com.king.pojo.Dog"/>
<bean id="cat1" class="com.king.pojo.Cat"/>
<bean id="cat2" class="com.king.pojo.Cat"/>
<bean id="user" class="com.king.pojo.User"/>
@Resource和@Autowired的区别:
在Spring4之后,要使用注解开发,必须要保证aop的包导入了!

使用注解需要导入 context约束,添加注解的支持
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
@Component:组件,放在类上,说明这个类被Spring管理了,就是bean
等价于
<!-- ApplicationContext.xml下的 指定要扫描的包,这个包下面的注解就会生效-->
<context:component-scan base-package="com.king.dao"/>
package com.king.dao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//等价于 <bean id="user" class="com.king.dao.User"/>
//@Component 组件
@Component
public class User {
// 等价于 <property name="name" value="king"/>
@Value("king")
public String name;
}
@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!功能都一样,都是组件的意思
这四个注解的功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
@Scope("prototype") 也是放在类上
xml与注解:
xml与注解最佳实践:
<!-- 指定要扫描的包,这个包下面的注解就会生效-->
<context:component-scan base-package="com.king"/>
<context:annotation-config/>
我们现在要完全不使用Spring的xml配置,全权交给Java来做
javaconfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能
package com.king.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这个注解的意思 就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
@Value("king")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
package com.king.config;
import com.king.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//这个也会被Spring容器托管,注册到容器中,因为它本来就是一个@Component,
// @Configuration代表这是一个配置类,跟之气前的beans.xml是一样的
@Configuration
@ComponentScan("com.king.pojo")
@Import(MyConfig2.class)
public class MyConfig {
//注册一个bean 就相当于之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法阿德返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User(); //就是返回要注入到bean的对象!
}
}
import com.king.config.MyConfig;
import com.king.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
@Test
public void test1(){
//如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User getUser = (User) context.getBean("getUser");
System.out.println(getUser.toString());
}
}
这种纯Java的配置方式,在SpringBoot中随处可见!
为什么要学习代理模式?因为这个就是SpringAOP的底层! 【SpringAOP和SpringMVC】
代理模式分类:
静态代理
动态代理
角色分析:
接口:
package com.king.demo01;
//租房
public interface Rent {
void rent();
}
真实角色:
package com.king.demo01;
//房东
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子!");
}
}
代理:
package com.king.demo01;
public class Proxy implements Rent {
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
host.rent();
seeHouse();
hetong();
fare();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房!");
}
//签租赁合同
public void hetong(){
System.out.println("中介签合同!");
}
//收中介费
public void fare(){
System.out.println("收中介费!");
}
}
租房的人:
package com.king.demo01;
public class Client {
public static void main(String[] args) {
//房东要出租房子
Host host = new Host();
//代理,中介帮房东出租房子,代理角色一般会有一些附属操作!
Proxy proxy = new Proxy(host);
//不用面对房东,直接跟中介交互即可!
proxy.rent();
}
}
代理模式的好处:
缺点:
需要了解两个类:Proxy:代理 , InvocationHandler:调用处理程序
动态生成代理类:
package com.king.demo04;
import com.king.demo03.Rent;
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);
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
//动态代理的本质,就是使用反射机制实现!
Object result = method.invoke(target, args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法!");
}
}
客户端:
package com.king.demo04;
import com.king.demo02.UserService;
import com.king.demo02.UserServiceImpl;
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色:不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//设置要代理的对象
pih.setTarget(userService);
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
提供声明式事务;允许用户自定义切面
【重点】使用AOP置入 需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
接口:
package com.king.service;
public interface UserService {
void add();
void delete();
void update();
void query();
}
实现类:
package com.king.service;
public class UserServiceImple implements UserService {
@Override
public void add() {
System.out.println("添加一个用户");
}
@Override
public void delete() {
System.out.println("删除一个用户");
}
@Override
public void update() {
System.out.println("修改一个用户");
}
@Override
public void query() {
System.out.println("查询一个用户");
}
}
编辑日志输出代码:
package com.king.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
/**
*
* @param method 要执行的目标对象的方法
* @param objects 参数
* @param target 目标对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] objects, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了!");
}
}
package com.king.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
/**
*
* @param returnValue 返回值
* @param method
* @param objects
* @param target
* @throws Throwable
*/
@Override
public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"返回的结果为:"+returnValue);
}
}
ApplcationContext.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
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean-->
<bean id="userService" class="com.king.service.UserServiceImple"/>
<bean id="log" class="com.king.log.Log"/>
<bean id="afterLog" class="com.king.log.AfterLog"/>
<!-- 方式一:使用原生Spring API接口-->
<!-- 配置aop 需要导入aop的约束 -->
<aop:config>
<!-- 切入点:expression:表达式 execution(要执行的位置! * * * * *)-->
<aop:pointcut id="pointcut" expression="execution(* com.king.service.UserServiceImple.*(..))"/>
<!-- 执行环绕增加-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
自定义类:
package com.king.diy;
public class DiyPointCut {
public void before(){
System.out.println("===========================方法执行前======================");
}
public void after(){
System.out.println("===========================方法执行后======================");
}
}
ApplicationContext.xml配置
<!-- 方式二-->
<bean id="diy" class="com.king.diy.DiyPointCut"/>
<aop:config>
<!--自定义切面,ref 要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.king.service.UserServiceImple.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
测试类:
import com.king.service.UserService;
import com.king.service.UserServiceImple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//注意点:动态代理 代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
自定义类:
package com.king.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//方式三:使用注解方式实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.king.service.UserServiceImple.*(..))")
public void before(){
System.out.println("=============方法执行前==========");
}
@After("execution(* com.king.service.UserServiceImple.*(..))")
public void after(){
System.out.println("=============方法执行后==========");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.king.service.UserServiceImple.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
//执行方法
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
ApplicationContext.xml配置
<!--方式三:注解实现-->
<bean id="annotationPointCut" class="com.king.diy.AnnotationPointCut"/>
<!-- 开启注解支持 JDK(默认proxy-target-class="false") cglib(proxy-target-class="true") -->
<aop:aspectj-autoproxy/>
测试类:
import com.king.service.UserService;
import com.king.service.UserServiceImple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//注意点:动态代理 代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
步骤:
数据源:
<?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
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
这里使用Spring提供的JDBC
-->
<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/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="admin888"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!-- 绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/king/mapper/*.xml"/>
</bean>
<!-- SqlSessionTemplate:就是我们使用的sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能使用构造器注入sqlSessionFatory,因为没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
接口实现类:
package com.king.mapper;
import com.king.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
//之前 所有操作,都是用sqlSession来执行。现在,都是用SqlSessionTemplate;
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
将实现类注入到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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<bean id="userMapper" class="com.king.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
测试类:
import com.king.mapper.UserMapper;
import com.king.pojo.User;
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 org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
@Test
public void test1() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper");
List<User> users = userMapper.selectUser();
for (User user : users) {
System.out.println(user);
}
}
}
事务ACID原则:
为什么需要事务?
原文:https://www.cnblogs.com/KingTL/p/12945251.html