文章目录
1、spring
1.1、简介
-
2002,首次推出了Spring框架的雏形:interface21框架!
-
Spring框架以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版。
-
Rod Johnson,spring Framework创始人,著名作者。
-
spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
-
SSH:Struct2 + Spring + Hibernate!
-
SSM:SpringMVC + Spring + MyBatis!
官网:https://spring.io/projects/spring-framework#overview
官方下载地址:
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.2.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
1.2、优点
- Spring是一个开源的免费的框架(容器)!
- Spring是一个轻量级的、非入侵的框架!
- 控制反转(IOC),面向切面编程(AOP)!
- 支持事务的处理,对框架整合的支持!
总结一句话:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!
1.3、组成
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EIVPvOhU-1629443558087)(C:\Users\TangDexin\AppData\Roaming\Typora\typora-user-images\1602676907693.png)]
1.4、扩展
- Spring Boot
- 一个快速开发的脚手架。
- 基于SpringBoot可以快速的开发单个微服务。
- 约定大于配置。
- SpringCloud
- SpringCloud是基于SpringBoot实现的。
因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC。承上启下的作用。
弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:"配置地狱!"
2、IOC理论推导
1.UserDao接口
2.UserDaoImpl实现类
3.UserService业务接口
4.UserServiceImpl业务实现类
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码,如果程序代码量十分大,修改一次的成本代价十分昂贵!
我们使用一个Set接口实现,已经发生了革命性的变化!
private UserDao userDao;
//利用set进行动态实现值的注入!
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
- 之前,程序是主动创建对象!控制权在程序员手上!
- 使用了set注入后,程序员不再具有主动性,而是变成了被动的接受对象!
这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了。系统的耦合度大大降低,可以更加专注的在业务的实现上!这是IOC的原型!
IOC本质
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。
3、HelloWorld
3.1实体类
public class Hello {
//属性
private String str;
//set和get方法
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
//重写tostring()
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
3.2配置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">
<!--使用spring创建对象,在Spring这些都称为Bean
id = 变量名
class = new 的对象
property 相当于给对象的属性赋值
-->
<bean id="hello" class="com.xin.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
3.3测试类
public class MyTest {
public static void main(String[] args) {
//获取spring上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象都在spring中管理了,我们需要使用就直接去里面取出来
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
3.4思考问题?
-
Hello对象是谁创建的?
hello对象是由Spring创建的
-
Hello对象的属性是怎么设置的?
hello对象的属性是由Spring容器设置的,
这个过程就叫控制反转:
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的.
反转:程序本身不创建对象,而变成被动的接收对象
依赖注入:就是利用set方法来进行注入的.
IOC是一种编程思想,由主动的编程变成被动的接收
可以通过newClassPathXmlApplicationContext去浏览一下底层源码
OK,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的loC,一句话搞定:对象由Spring来创建,管理,装配!
4、IOC创建对象的方式
1、使用无参构造创建对象(默认)
<bean id="user" class="com.xin.entity.User">
<property name="name" value="唐德鑫"/>
<property name="age" value="18"/>
</bean>
2、使用有参构造创建对象
<!--方式一:下标赋值-->
<bean id="user" class="com.xin.entity.User">
<constructor-arg index="0" value="小唐"/>
<constructor-arg index="1" value="18"/>
</bean>
<!--方式二:类型赋值(不建议使用)-->
<bean id="user" class="com.xin.entity.User">
<constructor-arg type="int" value="18"/>
<constructor-arg type="java.lang.String" value="小唐"/>
</bean>
<!--通过参数名赋值-->
<bean id="user" class="com.xin.entity.User">
<constructor-arg name="age" value="18"/>
<constructor-arg name="name" value="小唐"/>
</bean>
5、Spring配置
5.1、别名
<!--别名,如果添加了别名,我们也可以通过别名获取到这个对象-->
<alias name="user" alias="userNew"/>
5.2、Bean的配置
<!--
id: bean的唯一标识符,也就是相当于我们学的对象名
class:bean 对象所对应的全限定名:包名 + 类型
name:也是别名,而且name 可以同时取多个别名 空格和逗号分隔取多个别名
-->
<bean id="user" class="com.xin.entity.User" name="user2 u2,uu2">
<property name="name" value="唐德鑫"/>
<property name="age" value="18"/>
</bean>
5.3、import
这个import,一般用于团队开发,它可以将多个配置文件,导入合并为一个。多人合作开发时,我们可以利用import将所有人的beans.xml合并为一个总的!
<import resource="beans1.xml"/>
<import resource="beans1.xml"/>
<import resource="beans1.xml"/>
使用的时候,直接使用总的配置就可以了
6、依赖注入
6.1、构造器注入
6.2、Set方式注入【重点】
- 依赖注入:set注入!
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
1、复杂类型
package com.xin.entity;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2、真实测试对象
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;//爱好
private Map<String,String> card;//学生卡
private Set<String> games;
private String wife;
private Properties info;
}
3、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.xin.entity.Student">
<!--方式一:普通注入-->
<property name="name" value="小唐"/>
</bean>
</beans>
4、测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
}
}
完善注入信息:
<bean id="student" class="com.xin.entity.Student">
<!-- 普通注入 -->
<property name="name" value="唐德鑫"/>
<!-- Bean注入 -->
<property name="address" ref="address"/>
<!-- 数组注入 -->
<property name="books">
<array>
<value>三国演义</value>
<value>西游记</value>
<value>水浒传</value>
</array>
</property>
<!-- List注入 -->
<property name="hobbys">
<list>
<value>唱</value>
<value>跳</value>
<value>rap</value>
</list>
</property>
<!-- Map注入 -->
<property name="card">
<map>
<entry key="sfz" value="3607230000000000"/>
<entry key="xyk" value="201811304"/>
</map>
</property>
<!-- Set注入 -->
<property name="games">
<set>
<value>王者荣耀</value>
<value>英雄联盟</value>
</set>
</property>
<!-- null注入 -->
<property name="wife">
<null/>
</property>
<!--特殊类型-->
<property name="info">
<props>
<prop key="学号">201811304</prop>
<prop key="性别">男</prop>
</props>
</property>
</bean>
6.3、拓展方式注入
c命名空间和p命名空间的使用:
<?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="user" class="com.xin.entity.User" p:name="袁狗头" p:age="18"/>
<!--c命名空间,通过构造器注入:construct-args-->
<bean id="user2" class="com.xin.entity.User" c:name="袁2" c:age="12"/>
</beans>
测试:
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
User user = (User) context.getBean("user2");
System.out.println(user);
}
注意:p命名和c命名空间不能直接使用,需要导入xml约束!
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
6.4、bean的作用域
1.单例模式(Spring默认机制)
<bean id="user" class="com.xin.entity.User" p:name="袁狗头" p:age="18" scope="singleton"/>
2.原型模式:每次从容器中get的时候,都会产生一个新对象!
<bean id="user" class="com.xin.entity.User" p:name="袁狗头" p:age="18" scope="prototype"/>
3.其余的request,session,application,这些个只能在web开发中使用
7、bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式!
- Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中有三种装配的方式
- 在xml中显示的配置
- 在Java中显示配置
- 隐式的自动装配bean 【重要】
7.1、测试
7.2、ByName自动装配
<bean id="dog" class="com.xin.entity.Dog"/>
<bean id="cat" class="com.xin.entity.Cat"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 beanid!
-->
<bean id="people" class="com.xin.entity.People" autowire="byName">
<property name="name" value="袁狗头"/>
</bean>
7.3、ByType自动装配
<bean id="dog" class="com.xin.entity.Dog"/>
<bean id="cat" class="com.xin.entity.Cat"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 beanid!
byType:会自动在容器上下文中查找,和自己对象属性类型相同的 bean!
-->
<bean id="people" class="com.xin.entity.People" autowire="byType">
<property name="name" value="袁狗头"/>
</bean>
小结:
- ByName的时候,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
- ByType的时候,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
7.4、使用注解实现自动装配
jdk1.5支持的注解,Spring2.5就支持注解了!
要使用注解须知:
- 导入约束: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>
@Autowired
直接在属性上使用即可!也可以在set方式上使用!
使用@Autowired 我们可以不用编写set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字ByName!
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null
@Autowired(required=false)
//如果@Autowired的属性required为false 说明这个对象可以为null否则不允许为空
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=“xxx”)去配合@Autowired的使用,指定一个唯一的bean对象注入!
public class People {
@Autowired
@Qualifier(value = "dog111")
private Dog dog;
@Autowired
private Cat cat;
private String name;
}
@Resource
public class People {
@Resource(name = "dog111")
private Dog dog;
@Resource(name = "cat")
private Cat cat;
private String name;
}
小结:
@Autowired和@Resource区别:
- 都是用来自动装配的,都可以放在属性字段上。
- @Autowired 通过byName的方式实现,而且必须要去这个对象存在!
- @Resource 默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就会报错。
8、使用注解开发
在Spring4之后,要使用注解开发,必须要保证aop的包导入了
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XN7fdCH4-1629443558090)(C:\Users\TangDexin\AppData\Roaming\Typora\typora-user-images\1603170127094.png)]
使用注解需要导入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
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
注解说明:
- @Component :组件,放在类上说明这个类被Spring管理了,就是bean。
- @Value:给属性注入值,可以放在属性说,也可以放在Set方法上。
1.bean
2.属性如何注入
@Component
public class User {
private String name;
//相当于<property name="name" value="小唐"/>
@Value("小唐")
public void setName(String name) {
this.name = name;
}
}
3.衍生的注解
@Component有几个衍生的注解,我们在web开发中会按照mvc三层架构分层!
-
dao 【@Repository】
-
service 【@Service】
-
controller 【@Controller】
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配bean
4.自动装配
@Autowired:自动装配,通过类型,名字
如果@Autowired不能唯一自动装配上属性,则需要通过
@Qualifier(value="xxx")去配合@Autowired的使用。
@Nullable:字段标记了这个注解,说明这个字段可以为null。
@Resource :默认通过byName的方式实现,如果找不到名字,则通过byType实现!
5.作用域
@Component
@Scope("prototype")
public class User {
private String name;
//相当于<property name="name" value="小唐"/>
@Value("小唐")
public void setName(String name) {
this.name = name;
}
}
6.小结
xml与注解:
- xml更加万能,适用于任何场合!维护简单方便
- 注解 不是自己的类使用不了,维护相对复杂
xml与注解最佳实践:
- xml用来管理bean;
- 注解只负责完成属性的注入;
- 我们在使用过程中,只需要注意一个问题:必须让注解生效就需要开启注解的支持!
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.xin"/>
<!--开启注解支持-->
<context:annotation-config/>
9、使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig是Spring的一个子项目,在Spring 4之后,它成为了一个核心功能
实体类:
//这个注解的意思,就是说明这个类被Springr接管了,注册到了容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("小唐")
public void setName(String name) {
this.name = name;
}
}
配置文件:
import com.xin.entity.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.xin.entity")
@Import(XinConfig2.class)
public class XinConfig {
// 注册一个bean 就相当于我们之前写的一个bean标签
// 这个方法的名字,就相当于bean标签中的id属性
// 这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入到bean的对象
}
}
测试类:
public class MyTest {
@Test
public void test01(){
//如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的calss对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(XinConfig.class);
User user = (User) context.getBean("getUser");
System.out.println(user.getName());
}
}
这种纯Java的配置方式,在SpringBoot中随处可见!
10、代理模式
为什么要学习代理模式?因为这就是SpringAOP的底层!【SpringAOP和SpringMVC】
代理模式的分类:
- 静态代理
- 动态代理
10.1、静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属工作
- 客户:访问代理对象的人
代码步骤:
- 接口
package com.xin.demo01;
//租房
public interface Rent {
public void rent();
}
2. 真实角色
//房东
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子");
}
}
- 代理角色
public class Proxy implements Rent{
private Host host;
public Proxy(Host host) {
this.host = host;
}
public Proxy(){}
public void rent() {
host.rent();
seeHouse();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
}
- 客户端访问代理角色
public class Client {
public static void main(String[] args) {
//房东要出租房子
Host host = new Host();
//代理,中介帮房东出租房子,但是呢,代理一般会有一些附属操作。
Proxy proxy = new Proxy(host);
//你不用面对房东,直接找中介即可
proxy.rent();
}
}
代理模式的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共业务也就交给代理角色!实现了业务的分工!
- 公共业务发生扩展的时候方便集中管理
缺点:
- 一个真实角色就会产生一个代理角色;代码量会翻倍,开发效率会变低
10.2、动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口—JDK动态代理
- 基于类:cglib
- Java字节码:javasist
需要了解两个类:Proxy :代理,InvocationHandler:调用处理程序
动态代理对象的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共业务也就交给代理角色!实现了业务的分工!
- 公共业务发生扩展的时候方便集中管理
- 一个动态代理类代理的是一个接口,一般就是对应一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
代码实现:
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);
log(method.getName());//通过反射获取方法名
return result;
}
public void log(String msg) {
System.out.println("执行了" + msg + "方法");
}
}
测试类:
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.delete();
}
}
11、AOP
11.1、什么是AOP
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2、AOP实现
11.2.1、aop实现方式一(使用原生的Spring API接口)
用户类 com.xin.service userService.class
package com.xin.service;
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
用户实现类 com.xin.service userServiceImpl.class
package com.xin.service;
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void select() {
System.out.println("查询了一个用户");
}
}
日志类 com.xin.log Log.class
public class Log implements MethodBeforeAdvice {
// 要执行的目标对象的方法
// objects:参数
// target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"方法被执行了");
}
}
日志类 com.xin.log AfterLog.class
public class AfterLog implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
}
}
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"
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 id="userService" class="com.xin.service.UserServiceImpl"/>
<bean id="log" class="com.xin.log.Log"/>
<bean id="afterLog" class="com.xin.log.AfterLog"/>
<!-- 方式一:使用原生的Spring API接口 -->
<!-- 配置AOP -->
<aop:config>
<!-- 切入点 -->
<aop:pointcut id="pointcut" expression="execution(* com.xin.service.UserServiceImpl.*(..))"/>
<!-- 执行环绕增强 -->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试类 myText.class
import com.xin.service.UserService;
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 = context.getBean("userService", UserService.class);
userService.add();
}
}
执行结果
com.xin.service.UserServiceImpl的add方法被执行了
增加了一个用户
执行了add方法,返回结果为:null
11.2.2、aop实现方式二(自定义类)
自定义切面类 com.xin.div DivPointCut.class
public class DivPointCut {
public void before(){
System.out.println("========方法执行前===========");
}
public void after(){
System.out.println("========方法执行后===========");
}
}
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"
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 id="userService" class="com.xin.service.UserServiceImpl"/>
<bean id="log" class="com.xin.log.Log"/>
<bean id="afterLog" class="com.xin.log.AfterLog"/>
<!-- 方式二:自定义类 -->
<bean id="div" class="com.xin.div.DivPointCut"/>
<aop:config>
<!-- 自定义切面 ref要引用的类 -->
<aop:aspect ref="div">
<!-- 切入点 -->
<aop:pointcut id="point" expression="execution(* com.xin.service.UserServiceImpl.*(..))"/>
<!-- 通知 -->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
测试类
import com.xin.service.UserService;
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 = context.getBean("userService", UserService.class);
userService.add();
}
}
测试结果
========方法执行前===========
增加了一个用户
========方法执行后===========
11.2.3、aop实现方式三(使用注解)
注解类 com.xin.div AnnotationPointCut.class
// 使用注解方式实现AOP
@Aspect //标注这个类是个切面
public class AnnotationPointCut {
@Before("execution(* com.xin.service.UserServiceImpl.*(..))")
public void before() {
System.out.println("===========方法执行前========");
}
@After("execution(* com.xin.service.UserServiceImpl.*(..))")
public void after() {
System.out.println("===========方法执行后========");
}
@Around("execution(* com.xin.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pj) throws Throwable {
System.out.println("环绕前" + pj);
// 执行方法
Object proceed = pj.proceed();
System.out.println("环绕后");
}
}
测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.delete();
}
}
测试结果
环绕前execution(void com.xin.service.UserService.delete())
===========方法执行前========
删除了一个用户
===========方法执行后========
环绕后
12、整合MyBatis
步骤:
- 导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关
- aop织入
- mybatis-spring
- 编写配置文件
- 测试
spring整合mybatis所需jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<!-- spring操作数据库的话,还需要一个spring-jdbc这个包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
</dependencies>
</project>
spring-mybatis整合
1、编写数据源
2、sqlSessionFactory
3、sqlSessionTemplate
4、需要给接口加实现类
5、将自己写的实现类,注入到spring容器中
6、测试使用
13、声明式事务
事务概念:
- 要么都成功,要么都失败!
- 事务在项目开发中十分重要,涉及到数据一致性的问题
- 确保完整性和一致性
事务的ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会被影响
spring中的事务管理
- 声明式事务
- 编程式事务
事务配置
<!-- 配置声明式事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 综合AOP实现事务的织入 -->
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 给哪些方法配置事务 -->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入 -->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.xin.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
14、Spring注解
// 开启注解支持
<context:annotation-config/>
-
@Autowired 自动装配,通过byname @Autowired(required=false) 字段允许为空
- @Nullable 字段标记了这个注解,说明这个字段可以为null
- @Qualifier(value = “cat”) 如果@Autowired不能自动装配上属性,则需要通过@Qualifier指定名字
-
@Resource 通过byname自动装配,byname找不到的话会根据bytype自动装配,都找不到就报错
- @Resource(name = “dog111”) 指定名称
-
@Component 组件 四个注解功能都是一样的,都是将某个类注册到Spring中,装配Bean
- @Controller --> controller
- @Service --> service
- @Repository --> dao
-
要么都成功,要么都失败!
-
事务在项目开发中十分重要,涉及到数据一致性的问题
-
确保完整性和一致性
事务的ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会被影响
spring中的事务管理
- 声明式事务
- 编程式事务
事务配置
<!-- 配置声明式事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 综合AOP实现事务的织入 -->
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 给哪些方法配置事务 -->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入 -->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.xin.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
14、Spring注解
// 开启注解支持
<context:annotation-config/>
- @Autowired 自动装配,通过byname @Autowired(required=false) 字段允许为空
- @Nullable 字段标记了这个注解,说明这个字段可以为null
- @Qualifier(value = “cat”) 如果@Autowired不能自动装配上属性,则需要通过@Qualifier指定名字
- @Resource 通过byname自动装配,byname找不到的话会根据bytype自动装配,都找不到就报错
- @Resource(name = “dog111”) 指定名称
- @Component 组件 四个注解功能都是一样的,都是将某个类注册到Spring中,装配Bean
- @Controller --> controller
- @Service --> service
- @Repository --> dao