本视频教程来自B站@遇见狂神说,有需要的朋友可以去搜索观看他的视频学习。
Spring : 春天 —>给软件行业带来了春天
2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。
2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。
很难想象Rod Johnson的学历 , 他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
Spring理念 : 使现有技术更加实用 . 本身就是一个大杂烩 , 整合现有的框架技术
官网 : http://spring.io/
官方下载地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/
GitHub : https://github.com/spring-projects
依赖:
<!-- 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>
总结一句话:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架
1.UserDao接口
2.UserDaoImpl 实现类
3.UserService 业务接口
4.UserServiceImpl 业务实现类
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我么需要根据用户的需求去修改源代码!如果程序代码量十分大,修改一次的成本代价时分昂贵!
我们使用一个set接口实现,已经发生了革命性的变化!
//利用set进行动态实现值的注入
public void setUser(User user) {
this.user = user;
}
这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了。系统的耦合性大大降低,可以更加专注在业务的实现上,这就是IOC的原型!
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
导入Jar包
注 : spring 需要导入commons-logging进行日志记录 . 我们利用maven , 他会自动下载对应的依赖项 .
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
编写代码
1、编写一个Hello实体类
package cn.silentcow.pojo;
/**
* Created by NiuLinXuan on 2020-05-11 14:24
*/
public class Hello {
private String str;
public Hello() {
}
public Hello(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
2、编写我们的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">
<!--使用Spring来创建对象,在Spring这些都成为Bean-->
<bean id="hello" class="cn.silentcow.pojo.Hello">
<property name="str" value="Spring"></property>
</bean>
</beans>
3、我们可以去进行测试了 .
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
修改案例一
我们在案例一中, 新增一个Spring配置文件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="MySQLImpl" class="cn.silentcow.dao.UserMySQLImpl"></bean>
<bean id="UserImpl" class="cn.silentcow.dao.UserImpl"></bean>
<bean id="UserOraclImpl" class="cn.silentcow.dao.UserOraclImpl"></bean>
<bean id="UserServiceImpl" class="cn.silentcow.service.UserServiceImpl">
<property name="user" ref="UserOraclImpl"></property>
</bean>
</beans>
测试!
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
serviceImpl.getUser();
}
思考问题?
这个过程就叫控制反转:
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。
反转:程序本身不创建对象,而变成被动的接收对象
依赖注入:就是利用set方法来进行注入的
IOC是一种编程思想,由主动的编程变成被动的接收
可以通过new ClassPathXmlApplicationContext去浏览一下底层源码
到现在,要实现不同操作,只需要在xml配置文件中进行修改,所谓的IoC,一句话搞定:对象由Spring来创建,管理,装配!
1.使用无参构造创建对象,默认
2.假如我们要使用有参构造创建对象
1.下标赋值
<!--第一种,下标赋值-->
<bean id="user" class="cn.silentcow.pojo.User">
<constructor-arg index="0" value="狂神说Java"></constructor-arg>
</bean>
2.类型
<!--第二种,通过类型创建,不建议使用-->
<bean id="user" class="cn.silentcow.pojo.User">
<constructor-arg type="java.lang.String" value="silentcow"></constructor-arg>
</bean>
3.参数名
<!--第三种,直接通过参数名来创建-->
<bean id="user" class="cn.silentcow.pojo.User">
<constructor-arg name="name" value="中国"></constructor-arg>
</bean>
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!
<!--第三种,直接通过参数名来创建-->
<bean id="user" class="cn.silentcow.pojo.User">
<constructor-arg name="name" value="中国"></constructor-arg>
</bean>
<!--起别名-->
<alias name="user" alias="userNew"></alias>
<!--
id: bean的唯一标识符,也就是相当于我们学的对象名
class:bean 对象所对应的全限定名 : 包名 + 类型
name:也是别名,而且name 可以同时起多个别名,中间可以用 空格 逗号 分号 隔离
-->
<bean id="UserT" class="cn.silentcow.pojo.UserT" name="t,t2;t3 t4">
<property name="name" value="你好"></property>
</bean>
这个import,一般用于团队开发使用,它课将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!
<import resource="beans1.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>
<!--hexoPostRenderEscape:<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">使用的时候,直接使用总的配置就可以了</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 6. 依赖注入:DI</span><br><span class="line"></span><br><span class="line">## 1. 概念:</span><br><span class="line"></span><br><span class="line">* 依赖注入:Dependency Injection,DI</span><br><span class="line">* 依赖:指Bean对象的创建依赖于容器 Bean对象的依赖资源</span><br><span class="line">* 注入:指Bean对象所依赖的资源,由容器来设置和装配</span><br><span class="line"></span><br><span class="line">## 2. 构造器注入</span><br><span class="line"></span><br><span class="line">## 3. set注入(重点)</span><br><span class="line"></span><br><span class="line">要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is .</span><br><span class="line"></span><br><span class="line">Address.java</span><br><span class="line"></span><br><span class="line">```java</span><br><span class="line">/**</span><br><span class="line"> * Created by NiuLinXuan on 2020-05-11 19:00</span><br><span class="line"> */</span><br><span class="line">public class Address {</span><br><span class="line"> private String address;</span><br><span class="line"></span><br><span class="line"> public String getAddress() {</span><br><span class="line"> return address;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> public void setAddress(String address) {</span><br><span class="line"> this.address = address;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> @Override</span><br><span class="line"> public String toString() {</span><br><span class="line"> return "Address{" +</span><br><span class="line"> "address='" + address + '\'' +</span><br><span class="line"> '}';</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>:hexoPostRenderEscape-->
Student.java
package cn.silentcow.pojo;
import java.util.*;
/**
* Created by NiuLinXuan on 2020-05-11 19:00
*/
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 +
'}';
}
}
1、常量注入
<bean id="Student" class="cn.silentcow.pojo.Student" name="student">
<!--常量注入-->
<property name="name" value="牛林轩"></property>
</bean>
2、Bean注入
注意点:这里的值是一个引用,ref
<bean id="address" class="cn.silentcow.pojo.Address">
<property name="address" value="咸阳"></property>
</bean>
<bean id="Student" class="cn.silentcow.pojo.Student" name="student">
<!--Bean注入-->
<property name="address" ref="address"></property>
</bean>
3、数组注入
<bean id="Student" class="cn.silentcow.pojo.Student" name="student">
<!--数组注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
</bean>
4、List注入
<bean id="Student" class="cn.silentcow.pojo.Student" name="student">
<!--list注入-->
<property name="hobbys">
<list>
<value>听音乐</value>
<value>写代码</value>
<value>看电影</value>
</list>
</property>
</bean>
5、Map注入
<bean id="Student" class="cn.silentcow.pojo.Student" name="student">
<!--map注入-->
<property name="card">
<map>
<entry key="身份证" value="610427199705170716"></entry>
<entry key="银行卡" value="6222622262222622222"></entry>
</map>
</property>
</bean>
6、set注入
<bean id="Student" class="cn.silentcow.pojo.Student" name="student">
<!--set注入-->
<property name="game" >
<set>
<value>CF</value>
<value>DNF</value>
<value>LOL</value>
</set>
</property>
</bean>
7、Null注入
<bean id="Student" class="cn.silentcow.pojo.Student" name="student">
<!--null注入-->
<property name="wife">
<null></null>
</property>
</bean>
8、Properties注入
<bean id="Student" class="cn.silentcow.pojo.Student" name="student">
<!--Properties注入-->
<property name="info">
<props>
<prop key="driver">123456</prop>
<prop key="gender">男</prop>
<prop key="username">root</prop>
<prop key="password">lxj521..</prop>
</props>
</property>
</bean>
测试结果:
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--P命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="cn.silentcow.pojo.User" p:name="silentcow" p:age="22"></bean>
<!--C命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="cn.silentcow.pojo.User" c:name="程序牛" c:age="22"></bean>
</beans>
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("UserBeans.xml");
// User user = (User) context.getBean("user");
User user = context.getBean("user2", User.class);
System.out.println(user);
}
<bean id="user" class="cn.silentcow.pojo.User" p:name="silentcow" p:age="22" scope="singleton"></bean>
<bean id="user2" class="cn.silentcow.pojo.User" c:name="程序牛" c:age="22" scope="prototype"></bean>
<bean id="cat" class="cn.silentcow.pojo.Cat"/>
<bean id="dog" class="cn.silentcow.pojo.Dog"/>
<bean id="person" class="cn.silentcow.pojo.Person" autowire="byName">
<property name="name" value="silentcow"></property>
</bean>
<bean class="cn.silentcow.pojo.Cat"/>
<bean class="cn.silentcow.pojo.Dog"/>
<bean id="person" class="cn.silentcow.pojo.Person" autowire="byType">
<property name="name" value="silentcow"></property>
</bean>
小结:
1.导入约束:context约束
2.配置注解的支持:context:annotation-config/
在spring配置文件中引入context文件头,以及开启属性注解支持!
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
">
<!--配置注解的支持-->
<context:annotation-config/>
</beans>
直接在属性上使用即可,也可以在set方式上使用!
使用Autowired 我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname
package cn.silentcow.pojo;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by NiuLinXuan on 2020-05-11 22:51
*/
public class Person {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
public Person(Cat cat, Dog dog, String name) {
this.cat = cat;
this.dog = dog;
this.name = name;
}
public Person() {
}
public Cat getCat() {
return cat;
}
public Dog getDog() {
return dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
此时配置文件内容:
<!--配置注解的支持-->
<context:annotation-config/>
<bean class="cn.silentcow.pojo.Cat"/>
<bean class="cn.silentcow.pojo.Dog"/>
<bean id="person" class="cn.silentcow.pojo.Person" autowire="byType">
<property name="name" value="silentcow"></property>
</bean>
【科普】:
@Autowired(required=false) 说明:false,对象可以为null;true,对象必须存对象,不能为null。
//如果允许对象为null,设置required = false,默认为true
@Autowired(required = false)
private Cat cat;
测试实验步骤:
1、配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!
<bean id="cat" class="cn.silentcow.pojo.Cat"/>
<bean id="cat2" class="cn.silentcow.pojo.Cat"/>
<bean id="dog" class="cn.silentcow.pojo.Dog"/>
<bean id="dog222" class="cn.silentcow.pojo.Dog"/>
2、没有加Qualifier测试,直接报错
3、在属性上添加Qualifier注解
@Autowired(required = false)
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog222")
private Dog dog;
private String name;
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=”xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入。
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String name;
@Resource 和@Autowired的区别:
使用注解开发,必须要保证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:component-scan base-package="cn.silentcow.pojo"/>
<!--配置注解的支持-->
<context:annotation-config/>
</beans>
1.bean
//等价于 <bean id="user" class="cn.silentcow.pojo.User"></bean>
//@Component组件
@Component
public class User {
public String name;
}
}
2.属性如何注入
@Component
public class User {
public String name;
//相当于: <property name="name" value="silentcow"></property>
@Value("silentcow")
public void setName(String name) {
this.name = name;
}
}
3.衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层
4.自动装配
- @Autowired:是按类型自动转配的,名字
如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
- @Nullable 字段标记了这个注解,说明这个字段可以为null
- @Resource 自动装配通过名字,类型
5.作用域
@Component
@Scope("prototype")
public class User {
public String name;
//相当于: <property name="name" value="silentcow"></property>
@Value("silentcow")
public void setName(String name) {
this.name = name;
}
}
6.小结
xml 与 注解:
xml 与 注解 最佳实践:
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="cn.silentcow.pojo"/>
<!--配置注解的支持-->
<context:annotation-config/>
package cn.silentcow.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Created by NiuLinXuan on 2020-05-12 16:00
*/
//这里的这个注解的意思,就是说明这个类被spring接管了,注册到了容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("silentcow") //属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
package cn.silentcow.config;
import cn.silentcow.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;
/**
* Created by NiuLinXuan on 2020-05-12 16:01
*/
//这个也会被spring容器接管,注册到容器中,因为它本来就是一个@Component
// @Configuration 代表这是一个配置类,就和我们之前看的beans.xml
@Configuration
@ComponentScan("cn.silentcow") //扫描包
@Import(MyConfig2.class) //引入另一个配置
public class MyConfig {
//注册一个Bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser() {
return new User(); //就是返回要注入到bean的对象
}
}
import cn.silentcow.config.MyConfig;
import cn.silentcow.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Created by NiuLinXuan on 2020-05-12 16:03
*/
public class MyTest {
@Test
public void test() {
//如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文啦获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User getUser = (User) context.getBean("getUser");
System.out.println(getUser.getName());
}
}
角色分析:
代码步骤:
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() {
}
public Proxy(Host host) {
this.host = host;
}
public void rent() {
seeHouse();
hetong();
fare();
host.rent();
}
//看房
public void seeHouse() {
System.out.println("中介带你看房");
}
//签合同
public void hetong() {
System.out.println("签合同");
}
//收中介费
public void fare() {
System.out.println("收中介费");
}
}
4.客户端访问代理角色
public class Client {
public static void main(String[] args) {
//房东要出租房子
Host host = new Host();
//找中介租房子,中介从房东那拿房源以及一些附属操作
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
代理模式的好处:
缺点:
package cn.silentcow.demo2;
/**
* Created by NiuLinXuan on 2020-05-12 18:17
*/
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
package cn.silentcow.demo2;
/**
* Created by NiuLinXuan on 2020-05-12 18:18
*/
//真实对象
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 query() {
System.out.println("查询了一个用户");
}
}
package cn.silentcow.demo2;
/**
* Created by NiuLinXuan on 2020-05-12 18:23
*/
public class UserServiceProxy implements UserService {
UserServiceImpl service;
public void setService(UserServiceImpl service) {
this.service = service;
}
public void add() {
log("add");
service.add();
}
public void delete() {
service.delete();
}
public void update() {
service.update();
}
public void query() {
service.query();
}
//日志方法
public void log(String msg) {
System.out.println("使用了" + msg + "方法。");
}
}
package cn.silentcow.demo2;
/**
* Created by NiuLinXuan on 2020-05-12 18:19
*/
public class Client {
public static void main(String[] args) {
UserServiceImpl service = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy();
proxy.setService(service);
proxy.add();
}
}
需要了解两个类:Proxy:代理, InvocationHandler:调用
Object invoke(Object proxy, 方法 method, Object[] args);
//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean 。
动态代理的好处:
/**
* Created by NiuLinXuan on 2020-05-12 19:49
*/
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 service = new UserServiceImpl();
//代理角色,不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(service);//设置要代理的对象
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
提供声明式事务:允许用户自定义切面
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
【重点】 使用AOP置入,需要导入一个依赖包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
首先编写我们的业务接口和实现类
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
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 query() {
System.out.println("查询了一个用户");
}
}
然后去写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强
public class Log implements MethodBeforeAdvice {
//method: 要执行的目标对象的方法
//args: 参数
//target : 目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName() + "的" + method.getName() + "被执行啦");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue:返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了" + method.getName() + "方法,返回结果为:" + returnValue);
}
}
最后去spring的文件中注册 , 并实现aop切入实现 , 注意导入约束 .
<?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
">
<!--使用Spring来创建对象,在Spring这些都成为Bean-->
<bean id="userService" class="cn.silentcow.service.UserServiceImpl"></bean>
<bean id="log" class="cn.silentcow.log.Log"/>
<bean id="afterLog" class="cn.silentcow.log.AfterLog"/>
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:expression:表达式,execution(要执行的的位置!* * * * *)-->
<aop:pointcut id="pointcut" expression="execution(* cn.silentcow.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加!-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解这一块 .
Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .
目标业务类不变依旧是userServiceImpl
第一步 : 写我们自己的一个切入类
public class DiyPointCut {
public void before() {
System.out.println("======方法执行前========");
}
public void after() {
System.out.println("=======方法执行后========");
}
}
去spring中配置
<!--方式二-->
<!--注册dean-->
<bean id="diy" class="cn.silentcow.diy.DiyPointCut"></bean>
<aop:config>
<!--自定义切面:ref 要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* cn.silentcow.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"></aop:before>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
测试:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
<!--方式三-->
<bean id="annotationPointCut" class="cn.silentcow.diy.AnnotationPointCut"></bean>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
//方式三:使用注解方式实现AOP
@Aspect
public class AnnotationPointCut {
@Before("execution(* cn.silentcow.service.UserServiceImpl.*(..))")
public void before() {
System.out.println("方法执行前");
}
@After("execution(* cn.silentcow.service.UserServiceImpl.*(..))")
public void after() {
System.out.println("方法执行后");
}
@Around("execution(* cn.silentcow.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
Object proceed = jp.proceed(); //执行方法
System.out.println("环绕后");
}
}
<?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">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-10-mybatis</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!-- 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>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>
</project>
1.导入相关jar包
2.编写配置文件
3.测试
public interface UserMapper {
public List<User> getUsers();
}
1、编写数据源配置
2、sqlSessionFactory
3、sqlSessionTemplate
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
">
<!--DataSource:使用spring的数据源替换mybatis的配置 c3p0 dbcp druid
我们这里使用spring提供的jdbc :
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="lxj521.."/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:cn/silentcow/mapper/*.xml"></property>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
</beans>
4、需要给接口加实现类 【】
UserMapperImpl
package cn.silentcow.mapper;
import cn.silentcow.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
/**
* Created by NiuLinXuan on 2020-05-13 20:55
*/
public class UserMapperImpl implements UserMapper {
//我们的所有操作,都使用sqlSession来 执行,在原来,现在都使用SqlSessionTemplate
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> getUsers() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.getUsers();
}
}
5、将自己写的实现类,注入到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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--注入-->
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="cn.silentcow.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"></property>
</bean>
</beans>
6、测试使用即可
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.getUsers()) {
System.out.println(user);
}
}
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> getUsers() {
return getSqlSession().getMapper(UserMapper.class).getUsers();
}
}
<bean id="userMapper2" class="cn.silentcow.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
事务ACID原则:
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" 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="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* cn.silentcow.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
思考:为什么需要事务?
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.silentcow.mapper.UserMapper">
<select id="getUsers" resultType="user">
select * from mybatis.user
</select>
<insert id="addUser" parameterType="User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
</mapper>
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"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
">
<!--DataSource:使用spring的数据源替换mybatis的配置 c3p0 dbcp druid
我们这里使用spring提供的jdbc :
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="lxj521.."/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:cn/silentcow/mapper/*.xml"></property>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" 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="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* cn.silentcow.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" 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="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 开启别名映射-->
<typeAliases>
<typeAlias type="cn.silentcow.pojo.User" alias="user"></typeAlias>
</typeAliases>
</configuration>
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<import resource="spring-dao.xml"></import>
<!--bean-->
<bean id="userMapper" class="cn.silentcow.mapper.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
UserMapperImpl.java
package cn.silentcow.mapper;
import cn.silentcow.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
/**
* Created by NiuLinXuan on 2020-05-13 20:55
*/
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> getUsers() {
User user = new User(9, "小明", "123123");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(6);
return mapper.getUsers();
}
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.getUsers()) {
System.out.println(user);
}
}
}
文章作者: silentcow