栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring

《尚硅谷》

一:spring:Helloworld

Spring 是轻量级的开源的 JavaEE 框架,基本组成如下:

01.新建项目之后,建lib目录。引入jar包,只需要引入最基本的包

02.在src中建立普通类
package com.atguigu.spring5;
//添加一个add方法
public class User {
    public void add()
    {
        System.out.println("add.....");
    }
}
03.建立Beans.xml,并且进行注册,实现控制的反转


    

04.建立测试类进行测试
package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void test()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        User user=context.getBean("user", User.class);
        System.out.println(user);
        user.add();
    }
}
05输出结果:

二:spring:IOC

1、什么是 IOC

(1)控制反转,把对象创建和对象之间的调用过程,交给 Spring 进行管理

(2)使用 IOC 目的:为了耦合度降低 (3)做入门案例就是 IOC 实现

2、 IOC 底层原理 (1) xml 解析、工厂模式、反射

2、 Spring 提供 IOC 容器实现两种方式:(两个接口)

(1) BeanFactory: IOC 容器基本实现,是 Spring 内部的使用接口,不提供开发人员进行使用 * 加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象

(2) ApplicationContext: BeanFactory 接口的子接口,提供更多更强大的功能,一般由开发人 员进行使用 * 加载配置文件时候就会把在配置文件对象进行创建

3.IOC的beans管理:创建对象与属性注入 有两种实现方式,(1)基于 xml 配置文件方式实现 (2)基于注解方式实现

01.IOC依赖注入:第一种注入方式:使用 set 方法进行注入 1 创建类,并且设置set方法
package com.atguigu.spring5;
 public class Book {
        //创建属性
        private String bname;
        private String bauthor;
        //创建属性对应的 set 方法
        public void setBname(String bname) {
            this.bname = bname;
        }
        public void setBauthor(String bauthor) {
            this.bauthor = bauthor;
        }
    }
2.xml中配置

        
        
    
3.测试
public class testspring5
{
    @Test
    public void test()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        
        Book book=context.getBean("book",Book.class);
        book.set();
    }
}
02.IOC依赖注入:第一种注入方式:使用 set 方法进行注入 1 创建类,并且设置有参构造
public class Orders
{
    private String oname;
    private String address;
    //有参数构造
    public Orders(String oname,String address) {
        this.oname = oname;
        this.address = address;
    }
}
2.xml配置

        
        
    
3.测试 03、注入属性-外部 bean 1.建立两个类 service 类和 dao 类
package com.atguigu.spring5.dao;

public interface UserDao {
    public void update();
}
package com.atguigu.spring5.dao;

public class UserDaoImpl implements UserDao {

    @Override
    public void update() {
        System.out.println("dao update...........");
    }
}

建立service

package com.atguigu.spring5.Service;

import com.atguigu.spring5.dao.UserDao;

public class UserService
{
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void add() {
        System.out.println("service add...............");
        userDao.update();
    }
}
2.xml 配置
    
        
    
    
3.测试
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void test()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService=context.getBean("userService", UserService.class);
        userService.add();
    }
}

04.集合等属性的xml注入 1。建立类:
package com.atguigu.spring5.dao;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Stu
{
    private String[] courses;
    //2 list 集合类型属性
    private List list;
    //3 map 集合类型属性
    private Map maps;
    //4 set 集合类型属性
    private Set sets;
    public void setSets(Set sets) {
        this.sets = sets;
    }
    public void setCourses(String[] courses) {
        this.courses = courses;
    }
    public void setList(List list) {
        this.list = list;
    }
    public void setMaps(Map maps) {
        this.maps = maps;
    }
}

2.xml注入
 
    
    
        
            java 课程
            数据库课程
        
    
    
    
    
        张三
        小三
    
    
        
        
            
                
                
            
        
        
        
            
                MySQL
                Redis
            
        
    
05. IOC 操作 Bean 管理(FactoryBean) 01.建立基本类
public class Course {
 public void setCname( String name)
 {
     System.out.println(name);
 }
}
02.工厂类
import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean {
    //定义返回 bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("abc");
        return course;
    }
    @Override
    public Class getObjectType() {
        return null;
    }
    @Override
    public boolean isSingleton() {
        return false;
    }
}
03.xml配置
 
    
04.测试
public void test3() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean3.xml");
Course course = context.getBean("myBean", Course.class);
System.out.println(course);
}
06. IOC 操作 Bean 管理(bean 作用域)

1)在 spring 配置文件 bean 标签里面有属性( scope)用于设置单实例还是多实例

(2) scope 属性值 第一个值 默认值, singleton,表示是单实例对象 第二个值 prototype,表示是多实例对象

07.演示 bean 生命周期
public Orders() {
        System.out.println("第一步 执行无参数构造创建 bean 实例");
    }
    private String oname;
    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用 set 方法设置属性值");
    }
    //创建执行的初始化的方法
    public void initMethod() {
        System.out.println("第三步 执行初始化的方法");
    }
    //创建执行的销毁的方法
    public void destroyMethod() {
        System.out.println("第五步 执行销毁的方法");
    }

xml配置

 
        
    

测试方法:

@Test
    public void testBean3() {
// ApplicationContext context =
// new ClassPathXmlApplicationContext("bean4.xml");
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("第四步 获取创建 bean 实例对象");
        System.out.println(orders);
//手动让 bean 实例销毁
        context.close();
    }

(1)通过构造器创建 bean 实例(无参数构造)

(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)

(3)把 bean 实例传递 bean 后置处理器的方法 postProcessBeforeInitialization

(4)调用 bean 的初始化的方法(需要进行配置初始化的方法)

( 5)把 bean 实例传递 bean 后置处理器的方法 postProcessAfterInitialization

(6) bean 可以使用了(对象获取到了)

(7)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

07. IOC 操作 Bean 管理(基于注解方式) 01.引入AOP.jar,注解开通自动扫描

02.创建普通类,添加注释

Spring 针对 Bean 管理中创建对象提供注解

(1) @Component

(2) @Service

(3) @Controller

(4) @Repository

package com.atguigu.spring5.auto;

import org.springframework.stereotype.Component;

@Component(value="service")//
public class Service {
    public void add() {
        System.out.println("service add.......");
    }
}
03.建立测试类
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void testBean3() {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        Service service=context.getBean("service",Service.class);
        service.add();
    }
}
三.spring:AOP 1、 AOP 底层使用动态代理

(1) 第一种 有接口情况,使用 JDK 动态代理 ⚫ 创建接口实现类代理对象,增强类的方法

(2) 第二种 没有接口情况,使用 CGLIB 动态代理

2.JDK 动态代理 01.创建接口和普通类
package com.atguigu.spring5.auto;

public interface UserDao {
    public int add(int a,int b);
    public String update(String id);
}
package com.atguigu.spring5.auto;

public class UserDaoImpl implements UserDao {
    @Override
    public int add(int a, int b) {
        return a+b;
    }
    @Override
    public String update(String id) {
        return id;
    }
}
02.创建代理类
public class JDKProxy {
    public static void main(String[] args) {
//创建接口实现类代理对象
 Class[] interfaces = {UserDao.class};
 UserDaoImpl userDao = new UserDaoImpl();
UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result:"+result);
    }
}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    //1 把创建的是谁的代理对象,把谁传递过来
//有参数构造传递
    private Object obj;
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }
    //增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws
            Throwable {
//方法之前
        System.out.println("方法之前执行...."+method.getName()+" :传递的参数..."+ Arrays.toString(args));
//被增强的方法执行
        Object res = method.invoke(obj, args);
//方法之后
        System.out.println("方法之后执行...."+obj);
        return res;
    }
}
3.基于 AspectJ 实现 AOP 操作

(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强

(2)语法结构: execution([权限修饰符] [返回类型] [类全路径] 方法名称 )

举例 1:对 com.atguigu.dao.BookDao 类里面的 add 进行增强 execution(* com.atguigu.dao.BookDao.add(…))

举例 2:对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强 execution(* com.atguigu.dao.BookDao.* (…))

01.新建普通类和增强方法类
package com.atguigu.spring5.auto;

import org.springframework.stereotype.Component;

//添加一个add方法
@Component
public class User {
    public void add()
    {
        System.out.println("add.....");
    }
}
package com.atguigu.spring5.auto;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class UserProxy {
    @Before(value = "execution(* com.atguigu.spring5.auto.User.add(..))")
    public void before() {//前置通知
        System.out.println("before......");
    }
}
02.xml中开启扫描和aop
 
    
03.测试
package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.auto.Service;
import com.atguigu.spring5.auto.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void testBean3() {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        User user=context.getBean("user",User.class);
        user.add();
    }
}

有多个增强类多同一个方法进行增强,设置增强类优先级

(1)在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

@Component

@Aspect

@Order(1)

public class PersonProxy

四.spring 事务

(1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操 作都失败

(2)典型场景:银行转账 * lucy 转账 100 元 给 mary * lucy 少 100, mary 多 100 2、事务四个特性(ACID)

(1)原子性

(2)一致性

(3)隔离性

(4)持久性

01.搭建事物基本环境

01.新建UserDao接口以及实现类
package com.atguigu.spring5.dao;

public interface UserDao
{
    public void reduceMoney();
    public void addMoney();
}

package com.atguigu.spring5.dao;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //lucy 转账 100 给 mary
//少钱
    @Override
    public void reduceMoney() {
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }
    //多钱
    @Override
    public void addMoney() {
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }
}
02.service类和测试方法
package com.atguigu.spring5.Service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
    //转账的方法
    public void accountMoney() {
//lucy 少 100
        userDao.reduceMoney();
//mary 多 100
        userDao.addMoney();
    }
}
package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.Service.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void testBean3() {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        UserService userService=context.getBean("userService",UserService.class);
        userService.accountMoney();
    }
}

03.xml文件配置


    
    
    
        
        
        
        
    
    
        
        
    

04.测试可以看到数据库中的变化:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eSZeADN3-1632797441202)(C:Users123AppDataRoamingTyporatypora-user-images1632795388631.png)]

05.修改上面的service模拟出现异常的情况
package com.atguigu.spring5.Service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
    //转账的方法
    public void accountMoney() {
//lucy 少 100
        try {
            userDao.reduceMoney();
            int i=10/0;//异常出现
            userDao.addMoney();
        }
        catch (Exception e)
        {

        }

//mary 多 100

    }
}

06…测试,可以看到测试的结果如下:

02.事物操作

在 Spring 进行声明式事务管理,底层使用 AOP 原理

01.xml配置
  
    
        
        
    

    
    
02.修改Service类

在 service 类上面( 或者 service 类里面方法上面)添加事务注解

(1) @Transactional,这个注解添加到类上面,也可以添加方法上面

(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务

(3)如果把这个注解添加方法上面,为这个方法添加事务

package com.atguigu.spring5.Service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
 @Transactional(propagation = Propagation.REQUIRED)
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
    //转账的方法

    public void accountMoney() {
//lucy 少 100
            userDao.reduceMoney();
            int i=10/0;//异常出现
            userDao.addMoney();
//mary 多 100
    }
}
03.测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-17yi3xcn-1632797441204)(C:Users123AppDataRoamingTyporatypora-user-images1632797075017.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mS2L5cCt-1632797441205)(C:Users123AppDataRoamingTyporatypora-user-images1632797084290.png)] 03.事物的传播行为

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/273897.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号