<span>Spring框架学习</span>
1. Spring的概述
1.1 Spring的简介
理念: 使现有的技术更加实用,本事就是一个大杂烩,整合现有的框架技术。
1.2 Spring的优点
- Spring是一个开源免费的框架。<mark>容器</mark>
- Spring是一个轻量级的框架,非侵入式的。
- 控制反转(IOC),面向切面编程(Aop)
- 对事务的支持,对框架的支持
……
1.3 概括
<mark>Spring</mark>是一个轻量级的控制反转(IOC)和面向切面(Aop)编程的<mark>容器</mark>(框架)。
2. Spring的组成
<mark>核心容器(Spring Core)</mark>
核心容器提供Spring框架的基本功能。Spring以bean的方式组织和管理Java应用中的各个组件及其关系。Spring使用BeanFactory来产生和管理Bean,它是工厂模式的实现。BeanFactory使用控制反转(IoC)模式将应用的配置和依赖性规范与实际的应用程序代码分开。
<mark>应用上下文(Spring Context)</mark>
Spring上下文是一个配置文件,向Spring框架提供上下文信息。Spring上下文包括企业服务,如JNDI、EJB、电子邮件、国际化、校验和调度功能。
<mark>Spring面向切面编程(Spring AOP)</mark>
通过配置管理特性,Spring AOP 模块直接将面向方面的编程功能集成到了 Spring框架中。所以,可以很容易地使 Spring框架管理的任何对象支持 AOP。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖 EJB 组件,就可以将声明性事务管理集成到应用程序中。
<mark>JDBC和DAO模块(Spring DAO)</mark>
JDBC、DAO的抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理,和不同数据库供应商所抛出的错误信息。异常层次结构简化了错误处理,并且极大的降低了需要编写的代码数量,比如打开和关闭链接。
<mark>对象实体映射(Spring ORM)</mark>
Spring框架插入了若干个ORM框架,从而提供了ORM对象的关系工具,其中包括了Hibernate、JDO和 IBatis SQL Map等,所有这些都遵从Spring的通用事物和DAO异常层次结构。
<mark>Web模块(Spring Web)</mark>
Web上下文模块建立在应用程序上下文模块之上,为基于web的应用程序提供了上下文。所以Spring框架支持与Struts集成,web模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
<mark>MVC模块(Spring Web MVC)</mark>
MVC框架是一个全功能的构建Web应用程序的MVC实现。通过策略接口,MVC框架变成为高度可配置的。MVC容纳了大量视图技术,其中包括JSP、POI等,模型来有JavaBean来构成,存放于m当中,而视图是一个街口,负责实现模型,控制器表示逻辑代码,由c的事情。Spring框架的功能可以用在任何J2EE服务器当中,大多数功能也适用于不受管理的环境。Spring的核心要点就是支持不绑定到特定J2EE服务的可重用业务和数据的访问的对象,毫无疑问这样的对象可以在不同的J2EE环境,独立应用程序和测试环境之间重用。
3. IOC(控制反转)理论推导
3.1 用户实际调用的是业务层,dao层他们不需要接触
- UserDao 接口
- UserDaoImpl 实现类
- UserService 接口
- UserServieImple 实现类
在之前的代码,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
我们可以使用<mark>set接口</mark>实现,已经发生了***性的变化
private UserDao userDao;
//利用set进行动态实现值得注入!
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
- 之前,程序是主动创建对象!控制权在程序员手中!
- 使用了set注入之后,控制权到了用户手中!
这种思想,从本质上解决了问题,程序员不用再去管理对象的创建了。系统的耦合性大大降低了,可以更加专注的在业务的实现上!这是IOC的原型!
3.2. IOC本质
控制反转(IOC):是一种设计思想,DI(依赖注入)是实现IOC的一种方法。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IOC容器,其实现方法是<mark>依赖注入</mark>(Dependency Injection,DI)
4. Spring的第一个程序 HelloSpring
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 + '\'' +
'}';
}
}
4.1 使用Spring来创建对象,在Spring这些都称为Bean
类型 变量名 = 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);
}
}
4.2 小结
到此为止,切蒂不用再去程序中改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,一句话:<mark>对象由Spring来创建,管理,装配!</mark>
<!-- ApplicationContext.xml 的bean中的property标签的属性 -->
ref:引用Spring容器中创建好的对象
value: 具体的值,基本数据类型!
5. IOC创建对象的方式
-
使用无参构造对象,默认~
-
假设我们要使用有参构造创建对象。
-
下标赋值
<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>
-
总结:在配置文件夹在的时候,容器中管理的对象就已经初始化了!
6. Spring配置
6.1 别名
<alias name="user" alias="user2"/>
6.2 Bean的配置
<!--
id: Bean的唯一标识符,也就是相当于我们的对象名
class: bean 对象所对应的全限定名: 包名 + 类型
name: 也是别名
-->
<bean id="user" class="com.king.pojo.User" name="user2"/>
6.3 import
import,一般用于团队开发使用,它可以将多个配置文件,导入合并为一个
<import resource="beans.xml"/>
7. 依赖注入
7.1 构造器注入
讲过了!
7.2 set方式注入【重点】
- 依赖注入:Set注入!
- 依赖: bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入!
【环境搭建】
- 复杂类型
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}
}
7.3 拓展方式
P命名空间和C命名空间
7.4 Bean的作用域
-
单例模式(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"/>
- 其余的request、session、application,这些只能在web开发中使用到!
8. Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式!
- Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中有三种装配的方式
- 在xml中显示的配置
- 在java中显示配置
- 隐式的自动专供诶bean【重要】
8.1 测试
环境搭建:一个人两个宠物
8.2 byName自动装配
<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>
8.3 byType自动装配
<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>
<mark>小结:</mark>
- byName的时候,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性和set方法的值一致!
- byType的时候,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
8.4 使用注解实现自动装配
jdk1.5支持的注解,Spring2.5就支持注解了!
<mark>要使用注解须知</mark>:
- 导入约束
- <mark>配置注解的支持:</mark> 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
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>
@Autowired注解
- 直接在属性上使用即可!也可以在set方式上使用!
- 使用Autowired我们可以不用编写set方法了,前提是这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName
科普:
@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;
@Resource注解
- @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
- 其次再进行默认的byName方式进行装配;
- 如果以上都不成功,则按byType的方式自动装配。
- 都不成功,则报异常。
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的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired 通过byType的方式实现,而且必须要求这个对象存在!【常用】
- @Resource 默认通过byName的方式实现,如果找不到名字,则通过byType实现! 如果两个都找不到的情况下,就报错!
- 执行顺序不同:@Autowired 通过byType的方式实现。@Resource 默认通过byName的方式实现。
9. 使用注解开发
在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>
9.1 bean
<mark>@Component</mark>:组件,放在类上,说明这个类被Spring管理了,就是bean
等价于
<!-- ApplicationContext.xml下的 指定要扫描的包,这个包下面的注解就会生效-->
<context:component-scan base-package="com.king.dao"/>
9.2 属性如何注入
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;
}
9.3 衍生的注解
@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!功能都一样,都是<mark>组件</mark>的意思
- dao 【@Repository】
- service 【@Service】
- controller 【@Controller】
这四个注解的功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
9.4 自动装配置
9.5 作用域
@Scope("prototype") 也是放在类上
9.6 小结
xml与注解:
- xml更加万能,适用于任何场合!维护简单方便
- 注解 不是自己的类不能使用,维护相对复杂
xml与注解最佳实践:
- xml用来管理bean;
- 注解只负责完成属性的注入;
- 我们在使用的过程中,只需要注意一个问题;必须让注解生效,就需要开启注解的支持
<!-- 指定要扫描的包,这个包下面的注解就会生效-->
<context:component-scan base-package="com.king"/>
<context:annotation-config/>
10. 使用Java的方式配置Spring
我们现在要完全不使用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中随处可见!
11. 代理模式
为什么要学习代理模式?因为这个就是SpringAOP的底层! 【SpringAOP和SpringMVC】
代理模式分类:
-
静态代理
-
动态代理
11.1 静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作。
- 客户:访问代理对象的人
接口:
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();
}
}
代理模式的好处:
- 可以是真实的角色的操作更加纯粹! 不用去关注一些公共的业务!
- 公共的业务交给代理角色,实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!
缺点:
- 一个真实角色 就会产生一个代理角色;代码量会翻倍!开发效率会变低~
11.2 动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类是动态生成的,不是写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口--JDK动态代理 【使用这个】
- 基于类:cglib
- java字节码实现:javasist
需要了解两个类:Proxy:代理 , InvocationHandler:调用处理程序
<mark>动态生成代理类</mark>:
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+"方法!");
}
}
<mark>客户端</mark>:
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();
}
}
12. AOP 面向切面编程
12.1 什么是AOP
12.2 AOP在Spring中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关,但是我们需要关注的部分,就是横切关注点。如:日志,安全,缓存,事务等等……
- 切面(Aspect):横切关注点 被模块化 的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。 即,它是类中的方法。
- 目标(Target):被通知对象
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知 执行的“地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
12.3 使用Spring实现AOP
【重点】使用AOP置入 需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
方式一:使用Spring的API接口 【主要是SpringAPI接口实现】
接口:
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>
方式二:自定义类来实现AOP 【主要是切面定义】
自定义类:
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();
}
}
13. 整合MyBatis
步骤:
- 导入相关jar包
- junit
- mybatis
- MySQL数据库
- Spring相关
- AOP置入
- mybatis-spring
- 编写配置文件
- 测试
13.1 回忆Mybatis
- 编写实体类
- 编写核心配置文件
- 编写接口
- 编写Mapper.xml
- 测试
13.2 MyBatis-Spring
- 编写数据源
- sqlSessionFactory
- sqlSessionTemplate
- 给接口加实现类
- 将自己写的实现类,注入到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"
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);
}
}
}
14. 声明式事务
14.1 回顾事务
- 把一组业务当成一个业务来做;<mark>要么都成功,要么都失败!</mark>
- 事务在项目开发中,十分重要,设计到数据的一致性问题,不能马虎!
- 确保完整性和一致性;
事务ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中。
14.2 Spring中的事务管理
- 声明式事务:AOP
- 编程式事务:需要在代码中,进行事务的管理
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况;
- 如果我们不在Spring中去配置声明式事务,我们就需要在代码中手动配置事务!
- 事务在项目的开发中,十分重要,涉及到数据的一致性和完整性问题,不容马虎!