Spring5学习笔记
Spring5学习笔记
1. 简介
spring理念:是现有的技术更加容易使用,本身是一个大杂烩。
- SSH:Struct2 + Spring + Hibernate
- SSM: SpringMVC + Spring + Mybatis
所要下载的jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7.RELEASE</version>
</dependency>
- spring是开源的免费的容器。
- spring是一个轻量级的,非入侵式的。
- 控制反转(IOC),面向切面编程 (AOP)。
- 支持事务处理,对框架整合的支持。
总结:spring是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架。
2.IOC理论
-
UserDao
public interface UserDao { void getUser(); }
-
UserDaoImp
public class UserDaoImpl implements UserDao{ @Override public void getUser() { System.out.println("默认获取用户接口"); } }
-
UserSevice
public interface UserService { void getUser(); }
-
UserServiceImp
public class UserServiceImpl implements UserService{ private UserDao userDao; @Override public void getUser() { userDao.getUser(); } }
5.测试
@Test
public void testGetUser(){
//用户实际调用的是业务层,dao层他们不需要接触
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(new UserDaoMysqlImpl());
userService.getUser();
}
在之前,用户的需求可能会影响原来的代码。
使用一个set。
//利用set进行动态实现值的注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
- 之前是主动创建对象,控制权在程序员手上。
- 使用set之后,是被动接受对象。
3. Hello Spring
pojo中
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
resource中
<?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
类型 变量名 = new 类型();
Hello hello = new Hello();
id: = 变量名
class = new 的对象
property 相当于给对象的属性设置一个值
-->
<bean id="hello" class="com.wang.pojo.Hello">
<property name="str" value="Spring"></property>
</bean>
</beans>
Test
@Test
public void testHello(){
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
//我们的对象现在都在Spring中管理了,我们要使用,直接去里面取出来就可以了
Hello hello = context.getBean("hello", Hello.class);
System.out.println(hello.toString());
}
<bean id="mysqlImpl" class="com.wang.dao.UserDaoMysqlImpl"/>
<bean id="UserDao" class="com.wang.dao.UserDaoImpl"/>
<bean id="UserServiceImpl" class="com.wang.service.UserServiceImpl">
<!-- 引用Spring容器中创建好的对象-->
<property name="userDao" ref="mysqlImpl"></property>
</bean>
4. IOC创建对象的方式
- 使用无参构造创建对象 (默认)
- 使用有参构造
下标赋值
<?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.wang.pojo.User">
<constructor-arg index="0" value="hou"/>
</bean>
</beans>
类型赋值(不建议使用)
<bean id="user" class="com.wang.pojo.User">
<constructor-arg type="java.lang.String" value="dong"/>
</bean>
直接通过参数名
<bean id="user" class="com.wang.pojo.User">
<constructor-arg name="name" value="hou"></constructor-arg>
</bean>
Spring类似于婚介网站!
你想不想要,对象都在里面。注册bean之后用不用都会被实例化。
5. Spring配置
别名
<bean id="user" class="com.wang.pojo.User">
<constructor-arg name="name" value="wang"></constructor-arg>
</bean>
<alias name="user" alias="user2aaa"/>
Bean的配置
- id:bean的id标识符
- class:bean对象所对应的类型
- name:别名,更高级,可以同时取多个别名。
import
一般用于团队开发,它可以将多个配置文件,导入合并为一个
<import resource="beans.xml"/>
6. DI依赖注入
构造器注入
set方式注入(重点)
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
- 复杂类型
public class Student {
private String name;
private Address address;
private String[] book;
private List<String> hobby;
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[] getBook() {
return book;
}
public void setBook(String[] book) {
this.book = book;
}
public List<String> getHobby() {
return hobby;
}
public void setHobby(List<String> hobby) {
this.hobby = hobby;
}
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.toString() +
", book=" + Arrays.toString(book) +
", hobby=" + hobby +
", card=" + card +
", game=" + game +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
public class Address {
private String adderss;
public String getAdderss() {
return adderss;
}
public void setAdderss(String adderss) {
this.adderss = adderss;
}
@Override
public String toString() {
return "Address{" +
"adderss='" + adderss + '\'' +
'}';
}
}
2、真实测试对象
<property name="book">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>三国演义</value>
<value>水浒传</value>
</array>
</property>
<!--List-->
<property name="hobby">
<list>
<value>唱歌</value>
<value>跳舞</value>
<value>看书</value>
</list>
</property>
<!--Map-->
<property name="card">
<map>
<entry key="身份证" value="778837485843737"/>
<entry key="银行卡" value="6336363733633737"/>
</map>
</property>
<!--Set-->
<property name="game">
<set>
<value>LOL</value>
<value>MOC</value>
<value>KED</value>
</set>
</property>
<!--null-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="driver">33888</prop>
<prop key="url">iii888</prop>
<prop key="username">root</prop>
<prop key="password">123445</prop>
</props>
</property>
</bean>
c 标签和p标签
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 + '}'; }}
<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="com.wang.pojo.User" p:name="旺旺" p:age="18"/>
<!--c命名空间注入,通过构造器注入:construct-->
<bean id="user2" class="com.wang.pojo.User" c:name="吴旺仔" c:age="18"/>
</beans>
bean的作用域
- 单例模式(默认)scope="singleton"
<bean id="use2" class="com.pojo.User" c:name="kun" c:age="19" scope="singleton"></bean>
- 原型模式: 每次从容器中get的时候,都产生一个新对象!scope="prototype"
<bean id="use2" class="com.pojo.User" c:name="kun" c:age="19" scope="prototype"></bean>
- 其余的request、session、application这些只能在web开放中使用!
7. Bean的自动装配
- 自动装配是Spring是满足bean依赖的一种方式
- Spring会在上下文自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
-
在xml中显示配置
-
在java中显示配置【下面会有笔记】
-
隐式的自动装配bean 【重要】
-
环境搭建:一个人有两个宠物
-
Byname自动装配:byname会自动查找,和自己对象set对应的值对应的id
保证所有id唯一,并且和set注入的值一致
-
Bytype自动装配:byType会自动查找,和自己对象属性相同的bean
保证所有的class唯一
public class Cat {
public void shout(){
System.out.println("miao~");
}
}
public class Dog {
public void shout(){
System.out.println("wang~");
}
}
public class People {
@Resource
private Dog dog;
@Resource
private Cat cat;
private String name;
public Dog getDog() {
return dog;
}
public Cat getCat() {
return cat;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"dog=" + dog +
", cat=" + cat +
", name='" + name + '\'' +
'}';
}
}
<?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="cat11" class="com.wang.pojo.Cat"/>
<bean id="dog" class="com.wang.pojo.Dog"/>
<!--byname会自动查找,和自己对象set对应的值对应的id-->
<!--<bean id="people" class="com.wang.pojo.People" autowire="byName">-->
<!--<property name="name" value="wangwang"></property>-->
<!--</bean>-->
<!--byType会自动查找,和自己对象属性相同的bean-->
<bean id="people" class="com.wang.pojo.People" autowire="byType">
<property name="name" value="wangwnag"></property>
</bean>
</beans>
使用注解自动装配
jdk1.5支持的注解,spring2.5支持的注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
导入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>
@Autowire
在属性上使用,也可以在set上使用
我们可以不用编写set方法了
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
@Nullable 字段标志的注解,说明这个字段可以为null
如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候
我们可以使用@Qualifier(value = "dog")去配合使用,指定一个唯一的id对象
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog")
private Dog dog;
private String name;
}
@Resource(name="dog")也可以
区别:
- @autowire通过byType实现,而且必须要求这个对象存在
- @resource默认通过byName实现,如果找不到,通过byType实现
8. 使用注解开发
在spring4之后,必须要保证aop的包导入
使用注解需要导入contex的约束
<?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>
- 属性如何注入
@Component
public class User {
@Value("dong")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 衍生的注解
@Component有几个衍生注解,会按照web开发中,mvc架构中分层。
- dao (@Repository)
- service(@Service)
- controller(@Controller)
这四个注解功能一样的,都是代表将某个类注册到容器中
- 作用域
@Scope("singleton")
//@Component 等价于 <bean id="user" class="com.wang.dao.User"/>
@Component
public class User {
//等价于 <property name="" value=""/>
@Value("WANGWNAG")
public String name;
}
小结:
xml与注解
- xml更加万能,维护简单
- 注解,不是自己的类,使用不了,维护复杂
最佳实践:
- xml用来管理bean
- 注解只用来完成属性的注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/>
<!-- 指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.wang.dao"/>
</beans>
9. 使用java方式配置spring
JavaConfig
Spring的一个子项目,在spring4之后,,他成为了核心功能
@Configuration
//这个也会被spring接管,注册到容器中,因为它本来就是一个@Component
//@Configuration代表这是一个配置类,和我们之前看到的beans.xml类似
public class WangConfig {
//注册一个bean,相当于我们之前写的一个bean标签
//这个方法中的名字getUser ,相当于bean标签中的名字
//返回值相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();
}
}
//这里这个注解的意思,就是说明这个类被spring接管,注册到容器中
@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 + '\'' +
'}';
}
}
这种纯java配置方式
在springboot中,随处可见
10、代理模式
10.1、静态代理模式
角色分析
- 抽象角色:一般会使用接口或者抽象类
public interface Rent {
public void rent();
}
- 真实角色:被代理的角色
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
- 代理角色:代理真实角色,代理真实角色后,一般会由其他的操作
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
host.rent();
}
public void seeHouse(){
System.out.println("中介带你去看房");
}
public void heTong(){
System.out.println("签订合同");
}
public void fare(){
System.out.println("收取中介费");
}
}
- 客户:访问代理对象的人
public class Clince {
public static void main(String[] args) {
//房东要出租房子
Host host = new Host();
//代理,中介帮房东出租房子,会有其他附属操作
Proxy proxy = new Proxy(host);
proxy.seeHouse();
//不用找房东,直接找中介租房子
proxy.rent();
proxy.heTong();
proxy.fare();
}
}
代理模式的好处
- 可以使真实角色的操作更加纯粹,不用取关注一次额公共的业务
- 公共业务交给代理角色,实现业务的分工
- 公共业务发生扩展的时候,方便集中管理
10.2、加深理解静态模式
抽象角色:一般会使用接口或者抽象类
public interface UserService {
public void add();
public void delete();
public void updata();
public void query();
}
真实角色:被代理的角色
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void updata() {
System.out.println("更新了一个用户");
}
@Override
public void query() {
System.out.println("查看了一个用户");
}
}
代理角色:代理真实角色,代理真实角色后,一般会由其他的操作
public class UserServiceProxy implements UserService{
private UserServiceImpl userService;
public UserServiceProxy() {
}
public UserServiceProxy(UserServiceImpl userService) {
this.userService = userService;
}
@Override
public void add() {
log("add");
System.out.println("增加了一个用户");
}
@Override
public void delete() {
log("delete");
System.out.println("删除了一个用户");
}
@Override
public void updata() {
log("updata");
System.out.println("更新了一个用户");
}
@Override
public void query() {
log("query");
System.out.println("查看了一个用户");
}
//日志方法
public void log(String msg){
System.out.println("使用了"+msg+"方法");
}
}
客户:访问代理对象的人
public class Clince {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy(userService);
proxy.add();
}
}
10.3、动态代理模式
- 动态代理和静态代理角色一样
- 动态代理的代理类实动态生成的,不是我们直接写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
基于接口-------JDK动态代理
基于类----------cglib
java字节码实现-------java'si's't
需要了解两个类:Proxy InvocationHandler
抽象角色:一般会使用接口或者抽象类
public interface Rent {
public void rent();
}
真实角色:被代理的角色
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
动态生成代理类
//我们会用这个类自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler{
// Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
// new Class<?>[] { Foo.class },
// handler);
//被替代的接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
@Override
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用反射机制实现
seeHouse();
Object result = method.invoke(rent, args);
heTong();
return result;
}
public void seeHouse(){
System.out.println("中介带你去看房");
}
public void heTong(){
System.out.println("签订合同");
}
}
访问代理对象测试
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色,现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();//这里的proxy就是动态生成的,我们并没有写它
proxy.rent();
}
}
这样的话可以把动态生成代理类写成一个工具类
//我们会用这个类自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler{
// Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
// new Class<?>[] { Foo.class },
// handler);
//被替代的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用反射机制实现
log("add");
Object result = method.invoke(target, args);
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.add();
}
}
11、AOP
导入所需依赖jar包
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
方法一:使用spring接口【springAPI接口实现】
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
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("查看一个用户");
}
}
public class BeforeLog 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);
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean-->
<bean id="userService" class="com.wang.service.UserServiceImpl"/>
<bean id="beforLog" class="com.wang.log.BeforeLog"/>
<bean id="afterLog" class="com.wang.log.AfterLog"/>
<!--方式一:使用原生态的Spring API接口-->
<!-- 配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:execution()表达式,execution(要执行的位置!)-->
<aop:pointcut id="point" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="beforLog" pointcut-ref="point"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="point"/>
</aop:config>
</beans>
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
方法二:自定义来实现AOP【主要是切面定义】
public class DiyPointcut {
public void beforeLog(){
System.out.println("==========方法执行前============");
}
public void afterLog(){
System.out.println("==========方法执行后============");
}
}
<!--方式二:自定义类-->
<bean id="diy" class="com.wang.diy.DiyPointcut"/>
<aop:config>
<!--自定义切面,ref要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="beforeLog" pointcut-ref="point"/>
<aop:after method="afterLog" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
方法三:注解方式
@Aspect //标志这个类是一个切面
public class AnnotationPointcut {
//@Before("execution(* com.wang.service.UserServiceImpl.*(..))") 切入点
//方法类似通知
@Before("execution(* com.wang.service.UserServiceImpl.*(..))")
public void befor(){
System.out.println("=============方法执行前=================");
}
@After("execution(* com.wang.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("=============方法执行后=================");
}
@Around("execution(* com.wang.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
<!--方式三:通过注解-->
<bean id="annotationPointcut" class="com.wang.diy.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>
12. 整合mybatis
导入所需依赖jar包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
允许指定文件生成
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
<include>**/*.tld</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
mybatis核心配置文件
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration:核心配置文件-->
<configuration>
<typeAliases>
<package name="com.wang.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.wang.mapper.UserMapper"/>
</mappers>
</configuration>
public interface UserMapper {
public List<User> selectUser();
}
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration:核心配置文件-->
<mapper namespace="com.wang.mapper.UserMapper">
<select id="selectUser" resultType="user" >
select * from mybatis.user
</select>
</mapper>
Mybatis整合
方法一:
UserMapperImpl
public class UserMapperImpl implements UserMapper{
//我们所有的操作,原来都是用sqlSession来执行,现在用SqlSessionTemplate来实现
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public List<User> selectUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
mybatis-config.xml
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration:核心配置文件-->
<configuration>
<typeAliases>
<package name="com.wang.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
这里使用Spring提供的JDBC:org.springframework.jdbc.datasource -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/wang/mapper/UserMapper.xml"/>
</bean>
<!-- SqlSessionTemplate:就是我们要使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="userMapper" class="com.wang.mapper.UserMapperImpl"
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
test
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper mapperImpl = (UserMapper) context.getBean("userMapper2");
List<User> users = mapperImpl.selectUser();
for (User user : users) {
System.out.println(user);
}
}
方法二:
继承 SqlSessionDaoSupport
<?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">
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
这里使用Spring提供的JDBC:org.springframework.jdbc.datasource -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/wang/mapper/UserMapper.xml"/>
</bean>
</beans>
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
public List<User> selectUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.selectUser();
}
}
13. 声明式事务
- 要么都成功,要么都失败
- 十分重要,涉及到数据一致性
- 确保完整性和一致性
事务的acid原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作一个资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会被影响。
Spring中的事务管理
- 声明式事务
- 编程式事务
声明式事务
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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
这里使用Spring提供的JDBC:org.springframework.jdbc.datasource -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/wang/mapper/UserMapper.xml"/>
</bean>
<!-- SqlSessionTemplate:就是我们要使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg name="dataSource" ref="datasource"/>
</bean>
<!-- 结合AOP实现业务的织入
配置业务通知
-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="addUser" propagation="REQUIRED"/>
<tx:method name="deleteUser"/>
</tx:attributes>
</tx:advice>
<!-- 配置业务切入-->
<aop:config>
<aop:pointcut id="txPoint" expression="execution(* com.wang.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
<!-- -->
<!-- <bean id="userMapper" class="com.wang.mapper.UserMapperImpl">-->
<!-- <property name="sqlSessionTemplate" ref="sqlSession"/>-->
<!-- </bean>-->
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.wang.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
Mapper
UserMapper
public interface UserMapper {
public List<User> selectUser();
public int addUser(User user);
public int deleteUser(int id);
}
UserMapper.xml
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration:核心配置文件-->
<mapper namespace="com.wang.mapper.UserMapper">
<select id="selectUser" 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>
UserMapperImpl
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
public List<User> selectUser() {
User user = new User(10, "牛奶糖", "10000000");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(5);
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);
}
}
test
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper bean = (UserMapper) context.getBean("userMapper");
List<User> users = bean.selectUser();
for (User user : users) {
System.out.println(user);
}
}
}