1、Spring
1.1、简介
-
Spring:春---->给软件行业带来了春天
-
2002,首次推出了Spring框架的雏形: interface21框架
-
Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式
版 -
Rod Johnson,Spring Framework创始人,著名作者。很难想象Rod Johnson的学历,真的让好多人大吃一
惊,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学 -
spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架
-
SSH : Struct2 + Spring + Hibernate
-
SSM:SpringMvc + Spring + Mybatis
官网: https://spring.io/projects/spring-framework#overview
官方下载地址: http://repo.spring.io/release/org/springframework/spring
GitHub: https://github.com/spring:projects/spring-framework
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
1.2、优点
- Spring是一个开源的免费的框架(容器) !
- Spring是一个轻 量级的、非入侵式的框架!
- 控制反转(IOC),面向切面编程(AOP) !
- 支持事务的处理,对框架整合的支持!
总结一-句话: Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP) 的框架!
1.3、组成
1.4、拓展
在Spring的官网有这个介绍:现代化的Java开发!说白就是基于Spring的开发!
- Spring Boot
- 一个快速开发的脚手架
- 基于Spring Boot可以快速的开发单个微服务
- 约定大于配置
- Spring Cloud
- Spring Cloud是基于Spring Boot实现的
因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提 ,需要完全掌握Spring及
SpringMVC!承上启下的作用!
弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!”
2、IOC理论推导
- UserDao接口
- UserDaolmpl实现类
- UserService业务接口
- UserServicelmpl业务实现类
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!
如果代码量非常大,修改一次的成本代价十分昂贵
使用set接口实现
private UserDao userDao;
//利用set进行动态实现值得注入
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
- 之前,程序是主动创建对象!控制权在程序猿手上!
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象,系统耦合性大大降低,可以更加的专注在业务的实现上,这是IOC的原型
IOC本质
控制反转loC(Inversion of Control),是-种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是
IoC的另一种说法。没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序
中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖
对象的方式反转了
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为- -体,
Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。 在Spring中实现控制反转
的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)
3、HelloSpring
User.java
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--bean = 对象-->
<!--id = 变量名(标识)-->
<!--class = new的对象(一个类所在的位置,全类名)-->
<!--property 相当于给对象中的属性设值,其中必须要有set方法,否则无法注入-->
<!--value:给对象属性取值 ref:指向具体的对象(bean的id值)-->
<bean id="user" class="com.hbxy.pojo.User">
<property name="id" value="1"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
</beans>
Test.java
public class Test {
public static void main(String[] args) {
//获取上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//获取bean
User user = (User) context.getBean("user");
//输出结果
System.out.println(user.toString());
}
}
思考问题?
-
Hello 对象是谁创建的?
hello对象是由Spring创建的 -
Hello 对象的属性是怎么设置的?
hello对象的属性是由Spring容器设置的,
这个过程就叫控制反转:
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后 ,对象是由Spring来创
建的.
反转:程序本身不创建对象,而变成被动的接收对象.
I
依赖注入:就是利用set方法来进行注入的.
IOC是- -种编程思想,由主动的编程变成被动的接收.
可以通过newClassPathXmlApplicationContext去浏览一下底层源码 .
到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的
IoC,-一句话搞定:对象由Spring来创建,管理,装配!
4、IOC创建对象的方式
- 使用无参构造创建对象,默认。
- 使用有参构造
User.java
public class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
下标赋值
<?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="user" class="com.hbxy.pojo.User">
<constructor-arg index="0" value="root"/>
<constructor-arg index="1" value="123456"/>
</bean>
</beans>
类型赋值(不建议使用),引用类型必须全称,默认从上到下
<bean id="user" class="com.hbxy.pojo.User">
<!--引用类型必须全称-->
<constructor-arg type="java.lang.String" value="root"/>
<constructor-arg type="java.lang.String" value="123456"/> <!--分不清是哪个参数,不建议使用-->
</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="user" class="com.hbxy.pojo.User">
<constructor-arg name="username" value="root"/>
<constructor-arg name="password" value="123456"/>
</bean>
</beans>
Spring类似于婚介网站!
你想不想要,对象都在里面。注册bean之后用不用被实例化。
总结:在配置文件加载的时候,容器(applicationContext)中管理的对象就已经初始化(实例化)
5、Spring配置
5.1、别名
<bean id="user" class="com.hbxy.pojo.User">
<constructor-arg type="java.lang.String" value="root"/>
<constructor-arg type="java.lang.String" value="123456"/>
</bean>
<!--如果添加了别名,也可以通过别名获取到这个对象-->
<alias name="user" alias="userNew"/>
5.2、Bean的配置
- id:bean的id标识符
- class:bean对象所对应的类型(包名+类名)
- name:别名,更高级,可以同时取多个别名。
<bean id="userT" class="com.hbxy.pojo.UserT" name="userT1 userT2,userT3">
<property name="username" value="root"/>
</bean>
5.3、import
这个import,一般用于团队开发,可以将多个配置文件,导入合并一个
假设,项目中有多个人开发,这三个人负责不同的人开发,不同的类需要注册在不同的bean中,我们可以利用import,将所有人的beans.xml合并为总的
- 张三
- 李四
- 王五
- applicationContext.xml
使用的时候使用总的就可以了
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>
6、DI依赖注入
6.1、构造器注入
前面讲过
6.2、通过set方式注入【重点】
- 依赖注入:Set注入!
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
-
复杂类型
public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
-
真实测试对象
public class Student { private String name; private Address address; private String[] books; private List<String> hobbies; private Map<String,String> card; private Set<String> games; private Properties info; private String wife; }
-
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="student" class="com.hbxy.pojo.Student"> <!--1.普通值注入--> <property name="name" value="小明"/> <property name="address" ref="address"/> </bean> </beans>
-
测试类
public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.getAddress()); } }
完善注入信息
<?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.hbxy.pojo.Address"> <property name="address" value="围场"/> </bean> <bean id="student" class="com.hbxy.pojo.Student"> <!--1.普通值注入--> <property name="name" value="小明"/> <!--2.Bean注入,ref--> <property name="address" ref="address"/> <!--3.数组注入--> <property name="books"> <array> <value>红楼梦</value> <value>三国演义</value> <value>西游记</value> <value>水浒传</value> </array> </property> <!--4.list注入--> <property name="hobbies"> <list> <value>学习</value> <value>看书</value> <value>敲代码</value> </list> </property> <!--5.map--> <property name="card"> <map> <entry key="身份证" value="130828199221213456"/> <entry key="电话" value="19822384587"/> <entry key="银行卡" value="6564512316512"/> </map> </property> <!--6.Set--> <property name="games"> <set> <value>LOL</value> <value>COC</value> <value>BOB</value> </set> </property> <!--7.NULL--> <property name="wife"> <null/> </property> <!--8.Properties--> <property name="info"> <props> <prop key="学号">18851004</prop> <prop key="性别">男</prop> <prop key="爱好">睡觉</prop> </props> </property> </bean> </beans>
6.3、拓展方式注入
我们可以使用p命名空间和c命名空间注入
官方解释:
使用!
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="userp" class="com.hbxy.pojo.User" p:username="root" p:password="123456"/>
<!--c命名空间注入,通过构造器注入-->
<bean id="userc" class="com.hbxy.pojo.User" c:_0="xiaoming" c:_1="188324"/>
</beans>
测试:
import com.hbxy.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("user.xml");
User user = (User) context.getBean("user");
System.out.println(user);
}
@Test
public void userTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("user.xml");
User user = context.getBean("userc", User.class);
System.out.println(user);
}
}
注意点:
c命名空间和p命名空间不能直接使用,需要导入xml约束!
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
6.4、bean的作用域
-
单例模式(Spring默认机制)(每次从容器中get的时候,都是一个对象)
<bean id="userc" class="com.hbxy.pojo.User" c:_0="xiaoming" c:_1="188324" scope="singleton"/>
-
原型模式(每次从容器中get的时候,都会产生新对象)
<bean id="userc" class="com.hbxy.pojo.User" c:_0="xiaoming" c:_1="188324" scope="prototype"/>
3.其余的request、session、application、这些只能在web开发中使用!
7、Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种自动装配的方式
- 在xml中显式的配置
- 在java中显示配置
- 隐式的自动装配bean【重要】
7.1、测试
环境搭建:一个人有两个宠物
7.2、ByName自动装配
<bean id="cat" class="com.hbxy.pojo.Cat"/>
<bean id="dog" class="com.hbxy.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 bean id7.3-->
<bean id="person" class="com.hbxy.pojo.Person" autowire="byName">
<property name="name" value="小明"/>
</bean>
7.3、ByType自动装配
<bean class="com.hbxy.pojo.Cat"/>
<bean class="com.hbxy.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象属性类型相同的bean-->
<bean id="person" class="com.hbxy.pojo.Person" autowire="byType">
<property name="name" value="小明"/>
</bean>
小结:
- byname的时候,需要保证所有bean的id唯一,并且这 个bean需要和自动注入的属性的set方法的值-致!
- bytype的时候,需要保证所有bean的class唯一, 并且这个bean需要和自动注入的属性的类型-致!
7.4、使用注解实现自动装配
jdk1.5支持的注解,spring2.5支持的注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
要使用注解须知:
-
导入约束(context约束)
-
配置注解的支持 (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 https://www.springframework.org/schema/context/spring-context.xsd"> <!--开启注解支持--> <context:annotation-config/> </beans>
@Autowire
直接在属性上使用即可,也可以在set方式上使用
使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在I0C (Spring) 容器中存在,且符合名字byname
public class People {
@Autowired(required=false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
@Nullable 字段标志的注解,说明这个字段可以为null
如果@Autowired自动装配环境比较复杂,也就是不同一个类中不同的id的bean很多。自动装配无法通过一个注解完成的时候
我们可以使用@Qualifier(value = "dog")去配合使用,指定一个唯一的id对象
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog")
private Dog dog;
private String name;
}
@Resource(name="dog")也可以,并且@Resource(name="dog") =@Autowired+@Qualifier(value = "dog")
区别:
- @autowire通过byType和byName实现,而且必须要求这个对象存在,不存在配合@Qualifier(value = "dog") 使用
- @resource默认通过byName和byType实现,如果找不到,通过@Resource(name="dog")实现
8、使用注解开发
在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
https://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>
1.bean
@Component//相当于<bean id="user" class="com.hbxy.pojo.User"/>
public class User {
public String name = "小明";
}
2.属性如何注入
@Component
public class User {
@Value("小明")
public String name;<property name="name" value="小明">
}
也可以放在set方法上
@Component
public class User {
public String name;
@Value("小明")
public void setName(String name) {
this.name = name;
}
}
3.衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照MVC三层架构分层
-
dao 【@Repository】
-
service 【@Service】
-
controller 【@Controller】
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
4.自动装配
见上边
5.作用域
@Component
@Scope("singleton")
public class User {
public String name;
@Value("小明")
public void setName(String name) {
this.name = name;
}
}
6.小结
xml与注解
- xml更加万能,维护简单
- 注解,不是自己的类,使用不了,维护复杂
最佳实践:
- xml用来管理bean
- 注解只用来完成属性的注入
- 需要开启注解支持
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.hbxy"/>
<!--开启注解支持-->
<context:annotation-config/
9、完全使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig是Spring的一一个子项目,在Spring 4之后,它成为了一-个核心功能!
@Configuration //这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component,@Configuration代表这是一个配置类, 就和我们之前看的beans.xml
@ComponentScan("com.hbxy.pojo")
@Import(Config2.class)
public class MyConfig {
@Bean
public User getUser(){
return new User();
}
}
@Component
public class User {
@Value("dong")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
这种纯java配置方式
在springboot中,随处可见
10、代理模式
为什么要学习代理模式?因为这就是SpringAOP的底层! 【SpringAOP 和SpringMVC】
代理模式的分类:
- 静态代理、
- 动态代理
10.1、静态代理
角色分析:
- 抽象角色:一般会使用接口或抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色之后,我们会做一些附属操作
- 客户:访问代理对象的人
1.接口
public interface Rent {
//租赁
public void rent();
}
2.真实角色
public class Host implements Rent{
public void rent() {
System.out.println("房东出租房子");
}
}
3.代理角色
public class Proxy implements Rent{
private Host host;
public Proxy(Host host) {
this.host = host;
}
public void rent() {
seeHouse();
host.rent();
fare();
}
public void seeHouse(){
System.out.println("看房子");
}
public void fare(){
System.out.println("收钱");
}
}
4.客户端访问代理角色
public class Clint {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
代理模式的好处: .
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共也就就交给代理角色!实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!
缺点:
- 个真实角色就会产生一个代理角色;代码量会翻倍开发效率会变低~
10.2、加深理解
代码:08-demo02
10.3、动态代理
- 动态代理和静态代理一样
- 动态代理类是动态生成的,不是我们直接写好的!
- 基于接口的动态代理和基于类的动态代理
- 基于接口:JDK动态代理 【使用】
- 基于类:cglib
- 基于字节码实现:javasist
需要了解两个类:Proxy:代理、InvocationHandler:调用处理程序
InvocationHandler
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 {
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(target, args);
return result;
}
}
Test.java
public class Clint {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
11、AOP
11.1、什么是AOP
AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能
的统一维护的一 -种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一重要内容,是
函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合
度降低,提高程序的可重用性,同时提高了开发的效率。
11.2、AOP在Spring中的应用
提供声明式事务:允许用户自定义切面
11.3、使用Spring实现Aop
重点:使用AOP织入,需要导入一个依赖包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
<scope>runtime</scope>
</dependency>
方式一:使用Spring的API 接口【主要是接口实现】
<?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
https://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.hbxy.service.UserServiceImpl"/>
<bean id="log" class="com.hbxy.log.Log"/>
<bean id="afterLog" class="com.hbxy.log.AfterLog"/>
<!--方式一:使用原生API 接口-->
<!--配置AOP:需要导入aop约束-->
<aop:config>
<!--切入点 :expression:表达式 execution(要执行的位置)-->
<aop:pointcut id="pointcut" expression="execution(* com.hbxy.service.UserServiceImpl.*(..))"/>
<!--执行环绕增强-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
Log.java
public class Log implements MethodBeforeAdvice {
//method: 要执行的目标对象的方法
//objects:参数
//target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
AfterLog.java
public class AfterLog implements AfterReturningAdvice {
/**
*
* @param returnValue:返回值
* @param method:被激活的方法
* @param args:方法的参数
* @param target
* @throws Throwable
*/
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"返回结果为"+returnValue);
}
}
Test.java
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
方式二:自定义来实现AOP【主要是切面定义】
<!--方式二:自定义类-->
<bean id="diy" class="com.hbxy.diy.DiyPointCut"/>
<aop:config>
<!--自定义切面-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.hbxy.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
方式三:使用注解实现
<bean id="annotationPointCut" class="com.hbxy.diy.AnnotationPointCut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
@Aspect //标注此类是切面类
public class AnnotationPointCut {
@Before("execution(* com.hbxy.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("方法执行前");
}
@After("execution(* com.hbxy.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("方法执行后");
}
@Around("execution(* com.hbxy.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint point) throws Throwable {
System.out.println("执行前");
Signature signature = point.getSignature();//获得签名
System.out.println("signature"+signature);
Object proceed = point.proceed();
System.out.println("执行后");
}
}
12、整合Mybatis
步骤:
- 导入依赖
- Junit
- mybatis
- mysql数据库
- aop织入
- mybatis-spring【new】
- 编写配置文件
- 测试
12.1、回忆Mybatis
- 编写实体类
- 编写Mapper接口
- 编写Mapper.xml
- 编写配置文件
- 测试
12.2、Mybatis-spring
- 编写数据源配置
- sqlSessionFactory
- sqlSessionTemplete
- 需要给接口加实现类
- 将自己写的实现类注入到spring中
- 测试使用
整合
方法一:
UserMapperImpl
package com.mapper;
import com.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public List<User> selectUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
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>
<typeAliases>
<package name="com.pojo"/>
</typeAliases>
</configuration>
spring-dao.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--data source-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true&
userUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="hdk123"/>
</bean>
<!--sqlsession-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<!--bound mybatis-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/mapper/UserMapper.xml"/>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="userMapper" class="com.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"></property>
</bean>
</beans>
test
import com.mapper.UserMapper;
import com.pojo.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
public class Mytest {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
方法二:
<?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">
<!--data source-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true&
userUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="hdk123"/>
</bean>
<!--sqlsession-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<!--bound mybatis-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/mapper/UserMapper.xml"/>
</bean>
<!--<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">-->
<!--<constructor-arg index="0" ref="sqlSessionFactory"/>-->
<!--</bean>-->
<!--<bean id="userMapper" class="com.mapper.UserMapperImpl">-->
<!--<property name="sqlSessionTemplate" ref="sqlSession"></property>-->
<!--</bean>-->
<bean id="userMapper2" class="com.mapper.UserMapperIml2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
package com.mapper;
import com.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperIml2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
13、声明式事务
1、回顾事务
- 把一组业务当成一个业务来做,要么成功,要么失败
- 事务在项目开发,十分的重要,涉及到数据的一致性问题
- 确保完整性和一致性
事务的ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化写到存储器中
2、Spring中的事务管理
- 声明式事务:AOP
- 编程式事务:需要在代码中,进行事务管理
思考:
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况下;
- 如果我们不在SPRING中去配置声明式事务,我们就需要在代码中手动配置事务!
- 事务在项目的开发中十分重要,设计到数据的一致性和完整性问题,不容马虎!
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-mapper.xml"/>
<bean id="userMapper" class="com.hbxy.mapper.Impl.UserMapperImpl"/>
</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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启注解支持-->
<context:annotation-config/>
<context:component-scan base-package="com.hbxy.*"/>
<!--加载外部配置文件-->
<context:property-placeholder location="classpath:db.properties" />
<!--DateSource:使用Spring的数据源替换Mybatis配置 c3p0 dbcp druid
这里使用Spring提供的JDBC-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</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/hbxy/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--<constructor-arg ref="dataSource" />-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务的通知-->
<tx:advice id="txActive" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性:new propagation=-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="select" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.hbxy.mapper.*.*(..))"/>
<aop:advisor advice-ref="txActive" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
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="LOG4J"/>
</settings>
<typeAliases>
<package name="com.hbxy.pojo"/>
</typeAliases>
</configuration>
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
jdbc.username=root
jdbc.password=123456