狂神bilibili第地址
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#learn
官网下载地址:https://repo.spring.io/ui/native/release/org/springframework/spring
GitHub:https://github.com/spring-projects/spring-framework
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<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、扩展
-
SpringBoot
- 一个快速开发的脚手架。
- 基于SpringBoot可以快速的开发单个微服务。
- 约定大于配置!
-
SpringCloud
- SpringCloud 是基于SpringBoot实现的。
2、IOC理论推导
1.UserDao接口
package com.ryh.dao;
public interface UserDao {
void getUser();
}
2.UserDaolmpl 实现类
package com.ryh.dao;
public class UserDaoImpl implements UserDao{
public void getUser() {
System.out.println("这是传统的方法");
}
}
3.UserService业务接口
package com.ryh.service;
public interface UserService {
void getUser();
}
4.UserServicelmpl 业务实现类
package com.ryh.service;
import com.ryh.dao.UserDao;
import com.ryh.dao.UserDaoImpl;
public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoImpl();
public void getUser() {
userDao.getUser();
}
}
5、测试
package com.ryh;
import com.ryh.service.UserService;
import com.ryh.service.UserServiceImpl;
public class MyTest {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
userService.getUser();
}
}
在我们之前的业务中,I用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
我们使用一个Set接口实现.已经发生了革命性的变化!
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
- 之前,程序是主动创建对象!控制权在程序猿手上!
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!
这种思想,从本质上解决了问题,我们程序猿不用再去管理对象的创建了。系统的耦合性大大降低,可以更加专注的在业务的实现上!这是IOC的原型!
IOC本质
控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是loC的另一种说法。没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述((XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是loC容器,其实现方法是依赖注入(Dependency Injection,Dl)。
3、HelloSpring
导入Jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
编写代码
1、编写一个Hello实体类
package com.ryh.pojo;
public class Hello {
private String name;
public Hello() {
}
public Hello(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Hello{" +
"name='" + name + '\'' +
'}';
}
}
2、编写我们的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="hello" class="com.ryh.pojo.Hello">
<property name="name" value="Spring" />
</bean>
</beans>
3、我们可以去进行测试了
import com.ryh.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
思考
- Hello 对象是谁创建的 ? 【hello 对象是由Spring创建的
- Hello 对象的属性是怎么设置的 ? hello 对象的属性是由Spring容器设置的
这个过程就叫控制反转 :
- 控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的
- 反转 : 程序本身不创建对象 , 而变成被动的接收对象 .
依赖注入 : 就是利用set方法来进行注入的.
IOC是一种编程思想,由主动的编程变成被动的接收
修改案例一
我们在案例一中, 新增一个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="userDaoImpl" class="com.ryh.dao.UserDaoImpl" />
<bean id="userServiceImpl" class="com.ryh.service.UserServiceImpl">
<property name="userDao" ref="userDaoImpl" />
</bean>
</beans>
测试
package com.ryh;
import com.ryh.service.UserService;
import com.ryh.service.UserServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
userServiceImpl.getUser();
}
}
到了现在 , 我们彻底不用再程序中去改动了 , 要实现不同的操作 , 只需要在xml配置文件中进行修改 , 所谓的IoC,一句话搞定 : 对象由Spring 来创建 , 管理 , 装配 !
4、IOC创建对象的方式
使用无参构造创建对象,默认
-
实体类 package com.ryh.pojo;
public class User {
private String name;
public User() {
System.out.println("这是user的无参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println(this.name);
}
}
-
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 = "user" class="com.ryh.pojo.User">
<property name="name" value="renyuhua" />
</bean>
</beans>
-
测试 import com.ryh.pojo.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
user.show();
}
}
使用有参构造创建
实体类
package com.ryh.pojo;
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println(this.name);
}
}
1、下标赋值
<bean id = "user" class="com.ryh.pojo.User">
<constructor-arg index="0" value="任宇华" />
</bean>
2、通过类型创建
<bean id = "user" class="com.ryh.pojo.User">
<constructor-arg type="java.lang.String" value="任宇华" />
</bean>
3、通过参数名创建
<bean id = "user" class="com.ryh.pojo.User">
<constructor-arg name="name" value="任宇华" />
</bean>
结论:在配置文件加载的时候。其中管理的对象都已经初始化了!
5、Spring配置
5.1、别名
<alias name="user" alias="u" />
5.2、Bean的配置
<bean id = "user" class="com.ryh.pojo.User" name="user2 user3">
<constructor-arg name="name" value="任宇华" />
</bean>
5.3、import
这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!
<import resource="beans.xml"/>
<import resource="bean1.xml"/>
<import resource="bean2.xml"/>
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
6、DI依赖注入
6.1、构造器注入
前面已经了解过
6.2、Set方式注入
- 依赖注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入!
复杂类型
Address.java
package com.ryh.pojo;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Student.java
package com.ryh.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> games;
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> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
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 +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
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="student" class="com.ryh.pojo.Student">
<property name="name" value="任宇华" />
</bean>
</beans>
MyTest.java
import com.ryh.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("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
完善注入信息
Address.java
package com.ryh.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 + '\'' +
'}';
}
}
Student.java
package com.ryh.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> games;
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> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
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.toString() +
", books=" + Arrays.toString(books) +
", hobbys=" + hobbys +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
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="address" class="com.ryh.pojo.Address">
<property name="address" value="中国" />
</bean>
<bean id="student" class="com.ryh.pojo.Student">
<property name="name" value="任宇华" />
<property name="address" ref="address" />
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property>
<property name="card">
<map>
<entry key="身份证" value="1111111111" />
<entry key="银行卡" value="2222222222" />
</map>
</property>
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<property name="wife">
<null />
</property>
<property name="info">
<props>
<prop key="学号">20181666554</prop>
<prop key="性别">男</prop>
<prop key="名字">任宇华</prop>
</props>
</property>
</bean>
</beans>
MyTest.java
import com.ryh.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("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
}
}
6.3、扩展方式注入
User.java
package com.ryh.pojo;
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.ryh.pojo.User" p:name="任宇华" p:age="20" />
<bean id="user2" class="com.ryh.pojo.User" c:age="22" c:name="任宇华" />
</beans>
测试
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user2");
System.out.println(user+user2);
}
注意点:p命名和c命名空间不能直接使用,需要导入xml约束!
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
6.4、bean的作用域
单例模式
测试
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
User user = (User) context.getBean("user2");
User user2 = (User) context.getBean("user2");
System.out.println(user==user2);
}
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
默认就是单例模式
原型模式
测试
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
每次从容器中get的时候都会产生一个新的对象
其余的request、session、application、这些个只能在web开发中使用到!
7、Bean的自动装配
- 自动装配是Spring满足bean依赖一种方式
- Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中有三种装配的方式:
? 1、在xml中显示的配置
? 2、在java中显示配置
? 3、隐式的自动装配bean
7.1、测试
1、环境搭建:一个人有两个宠物
Cat.java
package com.ryh.pojo;
public class Cat {
public void shout(){
System.out.println("miao~~~~");
}
}
Dog.java
package com.ryh.pojo;
public class Dog {
public void shout(){
System.out.println("wang~~~~");
}
}
People.java
package com.ryh.pojo;
public class People {
private Cat cat;
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
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="dog" class="com.ryh.pojo.Dog" />
<bean id="cat" class="com.ryh.pojo.Cat" />
<bean id="people" class="com.ryh.pojo.People">
<property name="name" value="任宇华" />
<property name="cat" ref="cat" />
<property name="dog" ref="dog" />
</bean>
</beans>
MyTest.java
import com.ryh.pojo.People;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people",People.class);
people.getCat().shout();
people.getDog().shout();
}
}
7.2、ByName自动装配
<bean id="people" class="com.ryh.pojo.People" autowire="byName">
<property name="name" value="任宇华" />
</bean>
7.3、ByType自动装配
<bean class="com.ryh.pojo.Dog" />
<bean class="com.ryh.pojo.Cat" />
<bean id="people" class="com.ryh.pojo.People" autowire="byType">
<property name="name" value="任宇华" />
</bean>
小结:
- byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
- bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
7.4、使用注解自动装配
jdk支持的注解,spring2.5就支持了
要使用注解须知:
? 1.导入约束 context
? 2.配置注解的支持 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方法了,前提是你这个自动装配的属性在lOC(Spring)容器中存在,且符合名字byname!
@Nullable 字段标记了这个注解,说明这个字段可以为nu11
public @interface Autowired {
boolean required() default true;
}
测试
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
<?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/>
<bean id="dog" class="com.ryh.pojo.Dog" />
<bean id="cat" class="com.ryh.pojo.Cat" />
<bean id="people" class="com.ryh.pojo.People" />
</beans>
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候、我们可以使用@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!
@Autowired
@Qualifier(value = "dog2")
private Dog dog;
<bean id="dog" class="com.ryh.pojo.Dog" />
<bean id="dog2" class="com.ryh.pojo.Dog" />
@Resource注解
@Resource
private Cat cat;
@Resource
private Dog dog;
@Resource和@Autowired区别
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType的方式实现,而且必须要求这个对象存在!
- @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!
- 执行顺序不同:@Autowired通过byType的方式实现
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
package com.ryh.pojo;
import org.springframework.stereotype.Component;
@Component
public class User {
public String name = "任宇华";
}
配置文件
<context:component-scan base-package="com.ryh.pojo" />
2、属性如何注入
public class User {
@Value("任宇华")
public String name;
}
@Component
public class User {
public String name;
@Value("任宇华")
public void setName(String name) {
this.name = name;
}
}
3、衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!
@Component
public class User {
}
-
dao【@Repository】 package com.ryh.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
}
-
service【@Service】 package com.ryh.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
}
-
controller【@Controller】 package com.ryh.controller;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
}
这四个注解的功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
4、作用域
@Scope("prototype")
public class User {
}
5、自动装配
@Resource和@Autowired
6、小结
-
xml与注解:
- xml更加万能,适用于任何场合!维护简单方便
- 注解不是自己类是用不了,维护相对复杂
-
xml与注解最佳实现
- xml用来管理bean
- 注解只完成属性的注入
- 我们在使用过程中,必须是注解生效,就要开启注解的支持
<context:component-scan base-package="com.ryh" />
<context:annotation-config/>
9、使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig 是Spring的一个子项目,在$pring 4之后,它成为了一个核心功能!
实体类
package com.ryh.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("任宇华")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置文件
package com.ryh.config;
import com.ryh.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;
@Configuration
@ComponentScan("com.ryh.pojo")
@Import(MyConfig.class)
public class MyConfig {
@Bean
public User getUser(){
return new User();
}
}
package com.ryh.config;
public class MyConfig2 {
}
测试类
import com.ryh.config.MyConfig;
import com.ryh.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("user", User.class);
System.out.println(user.getName());
}
}
10、代理模式
为什么要学习代理模式?
这就是SpringAOP的底层【SpringAOP和SpringMVC】
代理模式的分类:
10.1、静态代理
角色分析:
- 抽象角色:一般会使用接口护着抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象
1、接口
package com.ryh.demo01;
public interface Rent {
public void rent();
}
2、真实角色
package com.ryh.demo01;
public class Host implements Rent{
public void rent() {
System.out.println("房东要出租房子");
}
}
3、代理角色
package com.ryh.demo01;
public class Proxy implements Rent{
private Host host;
public Proxy(){
}
public Proxy(Host host){
this.host = host;
}
public void rent() {
seeHOuse();
host.rent();
hetong();
fare();
}
public void seeHOuse(){
System.out.println("中介带你看房");
}
public void hetong(){
System.out.println("签合同");
}
public void fare(){
System.out.println("收中介费");
}
}
4、客户端访问代理角色
package com.ryh.demo01;
public class Client {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
代理模式的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共也就就交给代理角色!实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!
缺点:
- 一个真实角色就会产生一个代理角色;代码量会翻倍,开发效率会变低
10.2、加深理解
1、接口
package com.ryh.demo02;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
2、真实角色
package com.ryh.demo02;
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("查询一个用户");
}
}
3、代理角色
package com.ryh.demo02;
public class UserServiceProxy implements UserService{
private UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
public void add() {
log("add");
userService.add();
}
public void delete() {
log("delete");
userService.delete();
}
public void update() {
log("update");
userService.update();
}
public void query() {
log("query");
userService.query();
}
public void log(String msg){
System.out.println("使用了"+msg+"方法");
}
}
4、客户端访问代理角色
package com.ryh.demo02;
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy();
proxy.setUserService(userService);
proxy.add();
}
}
10.3、动态代理
- 动态代理和静态代理角色一样
- 动态代理类是动态生成的,不是我们直接写好的
- 动态代理分为两大类
- 基于接口:JDK动态代理【使用】
- 基于类:cglib
- java字节码实现:Javassist
需要了解两个类:Proxy:代理,lnvocationHandler:调用处理程序
租房
1、接口
package com.ryh.demo3;
public interface Rent {
public void rent();
}
2、真实角色
package com.ryh.demo3;
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子");
}
}
3、代理角色
package com.ryh.demo3;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxylnvocationHandler implements InvocationHandler {
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seehouse();
Object result = method.invoke(rent, args);
fare();
return result;
}
public void seehouse(){
System.out.println("中介带着我看房子");
}
public void fare(){
System.out.println("收中介费");
}
}
4、客户端
package com.ryh.demo3;
public class Client {
public static void main(String[] args) {
Host host = new Host();
ProxylnvocationHandler handler = new ProxylnvocationHandler();
handler.setRent(host);
Rent proxy = (Rent) handler.getProxy();
proxy.rent();
}
}
角色
1、接口
package com.ryh.demo02;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
2、真实角色
package com.ryh.demo02;
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("查询一个用户");
}
}
3、代理角色
package com.ryh.demo4;
import com.ryh.demo3.Rent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxylnvocationHandler 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 {
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
4、客户端访问
package com.ryh.demo4;
import com.ryh.demo02.UserService;
import com.ryh.demo02.UserServiceImpl;
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
ProxylnvocationHandler handler = new ProxylnvocationHandler();
handler.setTarget(userService);
UserService proxy = (UserService) handler.getProxy();
proxy.add();
}
}
动态代理的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共也就就交给代理角色!实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!
- 一个动态代理类代理的是一个接口,一般就是一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
11、AOP
11.1、什么是AOP
AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4mVFgT0G-1633449992989)(spring.assets/1633435981430.png)]
11.2、Aop在Spring中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
- 切面((ASPECT)︰横切关注点被模块化的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知执行的“地点""的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
即Aop在不改变原有代码的情况下,去增加新的功能.
11.3、使用Spring实现AOP
【重点】使用AOP织入,需要导入一个依赖包!
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
<scope>runtime</scope>
</dependency>
使用Spring的API接口
UserService.java
package com.ryh.service;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
UserServiceImpl.java
package com.ryh.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 query() {
System.out.println("查询一个用户");
}
}
Log.java
package com.ryh.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
AfterLog.java
package com.ryh.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+o);
}
}
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">
<bean id="userService" class="com.ryh.service.UserServiceImpl" />
<bean id="log" class="com.ryh.log.Log" />
<bean id="afterLog" class="com.ryh.log.AfterLog" />
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.ryh.service.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="log" pointcut-ref="pointcut" />
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut" />
</aop:config>
</beans>
MyTest.java
import com.ryh.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
使用自定义类实现AOP
DiyPointCut.java
package com.ryh.diy;
public class DiyPointCut {
public void before(){
System.out.println("=====方法执行前=====");
}
public void after(){
System.out.println("=====方法执行后=====");
}
}
配置文件
<?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 id="userService" class="com.ryh.service.UserServiceImpl" />
<bean id="log" class="com.ryh.log.Log" />
<bean id="afterLog" class="com.ryh.log.AfterLog" />
<bean id="diy" class="com.ryh.diy.DiyPointCut" />
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="point" expression="execution(* com.ryh.service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="point" />
<aop:after method="after" pointcut-ref="point" />
</aop:aspect>
</aop:config>
</beans>
注解实现AOP
AnnotationPointCut.java
package com.ryh.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.ryh.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=====方法执行前=====");
}
@After("execution(* com.ryh.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("=====方法执行后=====");
}
@Around("execution(* com.ryh.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕前");
Signature signature = joinPoint.getSignature();
System.out.println("signature:"+signature);
Object proceed = joinPoint.proceed();
System.out.println("环绕后");
System.out.println(proceed);
}
}
配置文件
<?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 id="userService" class="com.ryh.service.UserServiceImpl" />
<bean id="log" class="com.ryh.log.Log" />
<bean id="afterLog" class="com.ryh.log.AfterLog" />
<bean id="annotationPointCut" class="com.ryh.diy.AnnotationPointCut" />
<aop:aspectj-autoproxy />
</beans>
12、整合Mybatis
步骤:
12.1、回忆Mybatis
1、编写实体类
package com.ryh.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
2、编写核心配置文件
<?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.ryh.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_ryh?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ryh/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3、编写接口
package com.ryh.mapper;
import com.ryh.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
}
4、编写Mapper.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="com.ryh.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from mybatis_ryh.user;
</select>
</mapper>
5、测试
import com.ryh.mapper.UserMapper;
import com.ryh.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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = build.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user : users) {
System.out.println(user);
}
}
}
12.2、Mybatis-Spring
官网:http://mybatis.org/spring/zh/index.html
1、编写数据源配置
2、sqlSessionFactory
3、sqlSessionTemplate
4、需要给接口加实现类
5、将自己写的实现类,注入到Spring中
6、测试
方式一
UserMapper.java
package com.ryh.mapper;
import com.ryh.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
}
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="com.ryh.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from mybatis_ryh.user;
</select>
</mapper>
UserMapperImpl.java
package com.ryh.mapper;
import com.ryh.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();
}
}
User.java
package com.ryh.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
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" />
<bean id="userMapper" class="com.ryh.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession" />
</bean>
</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>
<typeAliases>
<package name="com.ryh.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">
<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_ryh?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:com/ryh/mapper/UserMapper.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
</beans>
MyTest.java
import com.ryh.mapper.UserMapper;
import com.ryh.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.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
@Test
public void test2(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
方式二
UserMapperImpl2.java
package com.ryh.mapper;
import com.ryh.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
public List<User> selectUser() {
SqlSession sqlSession = getSqlSession();
return sqlSession.getMapper(UserMapper.class).selectUser();
}
}
applicationContext.xml
<bean id="userMapper2" class="com.ryh.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
测试
import com.ryh.mapper.UserMapper;
import com.ryh.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.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
@Test
public void test2(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
13、声明式事务
13.1、回顾事务
- 把一组业务当成一个业务来做;要么都成功,要么都失败!
- 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎!
- 确保完整性和一致性;
事务ACID原则:
- 原子性
- 一致性
- 隔离性
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再影响,被持久化的写入数据库中
13.2、spring中的事务管理
UserMapper.java
package com.ryh.mapper;
import com.ryh.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
public int addUser(User user);
public int deleteUser(@Param("id") int id);
}
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="com.ryh.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from mybatis_ryh.user;
</select>
<insert id="addUser" parameterType="user">
insert into mybatis_ryh.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
<delete id="deleteUser" parameterType="int">
delete from mybatis_ryh.user where id = #{id};
</delete>
</mapper>
UserMapperImpl.java
package com.ryh.mapper;
import com.ryh.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
public List<User> selectUser() {
User user = new User(6, "任宇华", "123456");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(6);
return mapper.selectUser();
}
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
User.java
package com.ryh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
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" />
<bean id="userMapper" class="com.ryh.mapper.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</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>
<typeAliases>
<package name="com.ryh.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"
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">
<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_ryh?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:com/ryh/mapper/UserMapper.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<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(* com.ryh.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
</aop:config>
</beans>
MyTest.java
import com.ryh.mapper.UserMapper;
import com.ryh.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class MyTest {
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
List<User> users = userMapper.selectUser();
for (User user : users) {
System.out.println(user);
}
}
}
|