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

Spring--狂神

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

Spring--狂神

Spring
    • 1、简介
    • 2、IOC本质
      • 通过 IOC创建对象
      • 创建对象的方式
    • 3、Spring配置
    • 4、依赖注入
      • 4.1 基于构造函数
      • 4.2 基于Setter
      • 4.3 拓展方式注入
    • 5、bean的作用域
    • 6、bean的自动装配
      • 6.1 ByName 自动装配
      • 6.2 ByType自动装配
      • 6.3 使用注解自动装配
    • 7、使用注解开发
    • 8、使用java类配置Spring
    • 9、AOP
      • 9.1 AOP概念
      • 9.2 AOP在Spring中的作用
      • 9.3 使用Spring实现AOP
      • 9.4 自定义类实现AOP
      • 9.5 使用注解实现AOP
    • 10、整合Mybatis
      • 10.1 回忆Mybatis
      • 10.2 MyBatis-Spring
      • 10.3 SqlSessionDaoSupport
    • 11、声明式事务

感谢狂神的分享:B站地址

1、简介
  • 2002,首次推出了Spring框架的雏形:interface21框架!

  • Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版。

  • Rod Johnson,Spring Framework创始人,著名作者。很难想象Rod Johnson的学历,真的让好多人大吃一惊,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。

  • Spring是一个开源框架,是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。

  • Spring是一个轻量级的 控制反转(IoC) 和 面向切面 (AOP)的 非入侵式 的容器框架。

官网:https://spring.io/projects/spring-framework#overview
官方下载地址:https://repo.spring.io/release/org/springframework/spring/
GitHub地址:https://github.com/spring-projects/spring-framework



    org.springframework
    spring-webmvc
    xxxx



    org.springframework
    spring-jdbc
    xxxx

2、IOC本质

控制反转IoC(Inversion of Control),是一种设计思想。DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制;控制反转后将对象的创建转移给第三方。个人认为所谓控制反转就是:获得依赖对象的方式反转了。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体。Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

通过 IOC创建对象
  1. 新建一个工程,创建实体类
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 + ''' +
                '}';
    }
}

导入spring-webmvc包


    org.springframework
    spring-webmvc
    5.3.20

  1. 创建



    

    
        
    
    

  1. 测试(成功获取Hello的实例,并且 str = “this is my spring” )
 //获取Spring的上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Object hello = context.getBean("hello");
System.out.println(hello.toString());

Hello对象是由Spring创建的,属性是由Spring容器设置的。
上面的过程就叫控制反转:

控制:谁来控制对象的创建:传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。
反转:程序本身不创建对象,而变成被动的接收对象。
依赖注入:就是利用set方法来进行注入的。
IOC是一种编程思想,由主动的编程变成被动的接收。

OK,到了现在,我们彻底不用在程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,一句话搞定:对象由Spring来创建,管理,装配!

创建对象的方式
public class User {
    private int id;
    private String name;

    public User(int id,String name) {
        System.out.println("--------这是有参构造方法--------");
        this.id = id;
        this.name = name;
    }
	//。。。省略 get / set 方法

1、使用无参构造创建对象,默认!


2、使用有参构造创建对象。

  1. 根据构造函数的属性名赋值

    
    

  1. 根据构造器参数类型赋值

    
    

  1. 根据构造器参数的下标赋值

    
    

3、Spring配置

别名



Bean的配置



    

import

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个

如下所示,将三个 xml 导入 applicationContext.xml 中,则applicationContext.xml就能引用其他三个xml定义的信息。




4、依赖注入

依赖注入 (DI) 是一个过程,对象仅通过构造函数参数、工厂方法的参数或对象实例在构造或从工厂方法返回。然后容器在创建 bean 时注入这些依赖项。这个过程基本上是bean本身的逆过程(因此称为 控制反转 ),通过使用类的直接构造或服务定位器模式来控制其依赖项的实例化或位置。
DI 存在两个主要变体:基于构造函数的依赖注入 和 基于 Setter 的依赖注入。

4.1 基于构造函数

基于构造函数的 DI 是 通过容器调用 具有多个参数的 构造函数来完成的 ,每个参数代表一个依赖项。上面已经讲过 ↑

4.2 基于Setter

基于 Setter 的 DI 是通过容器在调用无参数构造函数或无参数static工厂方法来实例化 bean 后,调用 bean 上的 setter 方法来完成的。

  • 依赖 :bean对象的创建依赖于容器
  • 注入 :bean对象中的所有属性,由容器来注入

1. 创建复杂类型:

//地址类
public class Address {
    private String address;
    // 省略get/set方法、构造方法
}
//学生类
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List hobbies;
    private Map card;
    private Set games;
    private String wife;
    private Properties info;
    // 省略get/set方法、构造方法
}
  1. xml中的注册信息


	
	
        
    

	
    
        
        

        
        

        
        
            
                红楼梦
                西游记
                水浒传
                三国演义
            
        

        
        
            
                打篮球
                看电影
                敲代码
            
        

        
        
            
                
                
            
        

        
        
            
                LOL
                COC
                BOB
            
        

        
        
            
        

        
        
            
                20220610
                发斯蒂芬
                678618597
            
        
    

4.3 拓展方式注入

我们可以使用p命名空间和c命名空间进行注入,需要导入xml约束


xmlns:p="http://www.springframework.org/schema/p"

xmlns:c="http://www.springframework.org/schema/c"

如下所示:p命名空间 对应 set 方法注入;c命名空间对应构造器注入




    
    

    
    

5、bean的作用域

Singleton(Spring默认)

Spring中bean的单例概念,与设计模式中的单例不同。GoF 单例采用硬编码,以便每个 ClassLoader 对特定类仅创建一个实例。Spring中的单例,是指Spring 容器只对类创建一个实例。




@Test
public void test(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
    User user = (User) context.getBean("user2",User.class);
    User user2 = (User) context.getBean("user2",User.class);
    System.out.println(user==user2);
}
//结果为:true

Prototype

与其他范围相比,Spring 不管理原型 bean 的完整生命周期。在某些方面,Java new运算符的替代品。容器实例化、配置和以其他方式组装原型对象并将其传递给客户端,而没有该原型实例的进一步记录。客户端代码必须清理原型范围的对象并释放原型 bean 拥有的昂贵资源。




@Test
public void test(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
    User user = (User) context.getBean("user2",User.class);
    User user2 = (User) context.getBean("user2",User.class);
    System.out.println(user==user2);
}
//结果为:false
6、bean的自动装配

自动装配是spring满足bean依赖的一种方式。spring会在上下文中自动寻找,并自动给bean装配属性,有以下三种方式:

  1. 在xml中显示的配置 (上面讲过)
  2. 在Java中显示的配置
  3. 隐式的自动装配bean【重要】

准备环境

// 狗狗
public class Dog{
	public void shout(){
		System.out.print("wang~~");
	}
}
//猫咪
public class Cat{
	public void shout(){
		System.out.print("miao~~");
	}
}
public class People{
	private Dog dog;
	private Cat cat;
	private String name;
	// 省略get、set方法
}
6.1 ByName 自动装配





    

6.2 ByType自动装配





    

小结:
ByName:要保证所有bean的id唯一,并且这个 id 和被装配类的set方法中的参数值相同。
ByType:要保证所有bean的 class 唯一,并且这个bean要和自动注入的类型一致

6.3 使用注解自动装配

使用注解须知:

  • 1、导入约束:context 约束
  • 2、配置注解的支持:context:annotation-config/



    


@Autowired

可作用在Setter 方法中,属性,构造函数中。也可以不写set方法,前提是你自动装配的属性在IOC容器中,且符合名字byname

@Nullable  字段标记了这个注解,说明这个字段可以为null   

public People(@Nullable String name) {
    this.name = name;
}
@Autowired  源码:
public @interface Autowired {
    boolean required() default true;
}

@Autowired(required = false)
//说明这个对象可以为null,否则不允许为空,即使为null也不会报错

如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候
我们可以使用 @Qualifier(value = “dog”) 去配合使用,指定一个唯一的id对象

public class People {

    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")	//指定xml中的 bean id
    private Dog dog;
    private String name;
}

@Resource

public class People {
    @Resource(name = "cat2")
    private Cat cat;
    @Resource
    private Dog dog;
}
@Resource@ Autowired
默认通过ByName的方式实现,如果找不到名字,则通过byType实现!通过ByType的方式实现,而且必须要求这个对象存在【常用】
J2EE提供,需要JDK1.6及以上:javax.annotation.Resource由Spring提供:org.springframework.beans.factory.annotation.Autowired
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
默认情况下它要求 依赖对象 必须存在。如果允许null值,设置required属性为false。如果查询的结果不止一个,那么@Autowired会根据名称来查找。如果我们想使用按名称装配,也可以结合@Qualifier注解一起使用。
7、使用注解开发
  • 确定已经导入aop的包
  • 增加注解支持 aop



    
    

  1. bean
//@Component 组件
//等价于

@Component
public class User {
    public String name;
}
  1. 属性如何注入
@Component
public class User {
    
    public String name;
    @Value("hardy")
    //相当于
    public void setName(String name) {
        this.name = name;
    }
}
  1. 衍生的注解

@Component 有几个衍生的注解,我们在web开发中,会按照mvc三层架构分层

  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】

这四个注解功能都是一样的,都是代表将某个类注册到spring容器中,装配bean

  1. 自动装配
- @Autowired:自动装配通过类型,名字
  如果autowired不能唯一自动装配上属性,则需要通过
- @Qualifier(value = "xxx")
- @Resource:自动装配通过名字,类型
- @Nullable:字段标记了这个注解,说明这个字段可以为null
  1. 作用域
@Component
@Scope("prototype")
public class User {

    public String name;
    @Value("hardy")
    //相当于
    public void setName(String name) {
        this.name = name;
    }
}
  1. 小结
  • xml与注解:
    • xml 更加万能,适用于任何场合,维护简单方便
    • 注解 不是自己的类使用不了,维护相对复杂
  • xml与注解的最佳实践:
    • xml用来管理 bean,注解只负责完成属性的注入
    • 生产过程中:唯一需要注意,想让注解生效,就必须开启注解的支持




8、使用java类配置Spring

配置类

@Configuration

@ComponentScan("com.kuang")		//扫描哪些包
@Import(BeanConfig2.class)		//导入另一个配置类
public class BeanConfig {

    //注册一个bean  
    //方法名: 标签中的 id;  返回值: 标签中class属性 
    @Bean
    public User getUser(){
        return new User();
    }
}

实体类

@Component
public class User {
    private  String name;
    public String getName() {
        return name;
    }
   	//value对应  标签中的 property -- value
    @Value("hardy")
    public void setName(String name) {
        this.name = name;
    }
}

测试类

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig 上下文来获取容器,
        // 通过配置类的class对象加载。
        ApplicationContext context = new AnnotationConfigApplicationContext(HardyConfig.class);
        User user = (User) context.getBean("getUser");//配置类的id名就是方法名
        System.out.println(user.getName());
    }
}
9、AOP 9.1 AOP概念

AOP(Aspect Oriented Programming) 面向切面编程,通过 预编译方式 和 运行期动态代理 实现程序功能的统一维护的一种技术。AOP是OOP的延伸,是Spring框架中的一个重要内容,也是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,降低耦合性,提高可用性

9.2 AOP在Spring中的作用

提供声明式事务;允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。就是于业务逻辑无关,但需要关注的部分,比如日志、安全、缓存、事务。。
  • 切面(Aspect):横切关注点被模块化的特殊对象(一个类)
  • 通知(Advice):切面需要完成的工作(类中的一个方法)
  • 目标(Target):被通知对象
  • 代理(proxy):向目标对象应用通知之后创建的对象
  • 切入点(pointCut):切面通知执行的 地点 的定义
  • 连接点(JoinPoint):与 切入点 匹配的 执行点

    SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
通知类型连接点实现接口
前置通知方法前org.springframework.aop.MethodBeforeAdvice
后置通知方法后org.springframework.aop.AfterReturningAdvice
环绕通知方法前后org.aopalliance.intercept.MethodInterceptor
异常抛出通知方法抛出异常org.springframework.aop.ThrowsAdvice
引介通知类中增加新的方法属性org.springframework.aop.IntroductionInterceptor

9.3 使用Spring实现AOP

使用AOP织入,需要导入依赖包


    
        org.aspectj
        aspectjweaver
        1.9.4
    

创建Service接口和实现类

//接口
public interface UserService {
    public void add();
    public String delete();
    public void update();
    public void select();
}
//实现类
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("add");
    }
    public String delete() {
        System.out.println("delete");
        return "删除了一条数据";
    }
    public void update() {
        System.out.println("update");
    }
    public void select() {
        System.out.println("select");
    }
}

log类

//在方法调用之前执行
public class BeforeLog implements MethodBeforeAdvice {

    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("before----------------------"+method.getClass().getName()+"类,执行了"+method.getName()+"方法");
    }
}

//方法调用之后执行
public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("after-------"+method.getClass().getName()+"类,执行了"+method.getName()+"方法,返回值是----"+returnValue);
    }
}

Spring核心配置文件




    
    
    
    

    
    
        
        
        
        
        
    
    

测试类

@Test
public void testLogAdd(){
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    UserService userService = context.getBean("userService", UserService.class);
    userService.add();
}

@Test
public void testLogDelete(){
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    UserService userService = context.getBean("userService", UserService.class);
    userService.delete();
}
9.4 自定义类实现AOP

自定义类:

public class DiyPointCut {
    public void before(){
        System.out.println("========方法执行前=========");
    }
    public void after(){
        System.out.println("========方法执行后=========");
    }
}

xml配置





    
        
        
        
        
        
    

9.5 使用注解实现AOP

自定义类,添加注解:

@Aspect
public class AnnotationAspect {
    @Before("execution(* com.kuang.service.UserService.*(..))")
    public void before(){
        System.out.println("方法执行前-------------------");
    }

    @After("execution(* com.kuang.service.UserService.*(..))")
    public void after(){
        System.out.println("-------------------方法执行后");
    }

    @Around("execution(* com.kuang.service.UserService.*(..))")
    public void around(ProceedingJoinPoint pj) throws Throwable {
        System.out.println("----环绕前----");

        Signature signature = pj.getSignature();//获得签名
        System.out.println("方法签名:"+signature);

        pj.proceed();//执行方法(必须显示调用,否则方法不执行)
        
        System.out.println("----环绕后----");
    }
}

xml文件配置:








执行结果:

----环绕前----
方法签名:String com.kuang.service.UserService.delete()
方法执行前-------------------
delete
-------------------方法执行后
----环绕后----
10、整合Mybatis 10.1 回忆Mybatis

导入相关jar包

  • Junit
  • mybatis
  • MySQL
  • spring相关
  • aop织入
  • mybatis-spring 【new】

    junit
    junit
    4.11



    mysql
    mysql-connector-java
    8.0.29



    org.mybatis
    mybatis
    3.5.10



    org.springframework
    spring-jdbc
    5.3.20



    org.aspectj
    aspectjweaver
    1.9.9.1



    org.mybatis
    mybatis-spring
    2.0.7


    org.springframework
    spring-webmvc
    5.3.20

Maven静态资源导出问题


    
        
            src/main/java
            
                ***.xml
            
            false
        
        
            src/main/resources
            
                ***.xml
            
            false
        
    

实体类

public class User {
    private int id;
    private String userName;
    private String userPwd;
}

Mapper接口

public interface UserMapper {
    //根据id查询用户
    User getUserById(int id);
}

Mapper.xml





    
    
    

配置文件


driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/stu?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456







    

    
        
        
    

    
        
            
            
                
                
                
                
            
        
    
    
        
    

MybatisUtils工具类:

public class MybatisUtils {
    
    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"development");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

测试:

@Test
public void getUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User userById = mapper.getUserById(1);
    System.out.println(userById);
}
10.2 MyBatis-Spring
  1. 编写数据源配置
  2. sqlSessionFactory
  3. sqlSessionTemplete

mybatis-spring.xml





    
    
    
        
        
        
        
    

    
    
        
        
        
        
        
        

    





    
    
        
        
        
        
        
    





    
    

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

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

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