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

spring学习(跟随狂神学习)

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

spring学习(跟随狂神学习)

spring学习 1、简介

Spring是一个轻量级控制反转(IOC)和面向切面(AOP)的容器框架

官网:https://spring.io/projects/spring-framework#overview

官方下载地址:http://repo.spring.io/release/org/springframework/spring

GitHub:https://github.com/spring-projects/spring-framework

架包:



    org.springframework
    spring-webmvc
    5.2.0.RELEASE




    org.springframework
    spring-jdbc
    5.2.0.RELEASE



优点:

1、spring是一个开源的免费的框架!

2、spring是一个轻量级的、非入侵式的框架!

3、控制翻转(IOC),面向切面编程(AOP)!

4、支持事务的处理,对框架整合的支持!

组成

拓展

springboot:

1、一个快速开发的脚手架

2、基于springboot可以快速开发单个微服务

3、约定大于配置

springCloud

springcloud是基于springboot实现的

弊端:配置十分繁琐

2、IOC理论推导

本质:获取对象的方式反转了。从原先由程序控制到程序员或者用户决定。

改变对象的创建方式;

3、注册Bean的方法

重点:(在配置文件加载的时候,容器中管理的对象流已经初始化了,即在读取bean.xml时就会走java中对应的构造器)

1、无参构造
 
2、有参数构造

1、通过下标index




    
        
    
    

2、通过数据类型添加(不推荐)


    
 

3、通过属性名添加


    

4、通过已经注册的bean来添加引用

4、spring配置说明 4.1 别名
 
4.2 bean的配置

1、name也是别名(分隔符用啥都可以,只能比alias好)


4.3 import

(一般用于团队开发,他可以将多个配置文件导入到一个配置文件中)



   

5、依赖注入 5.1 构造器注入

如上述

5.2 set方式注入(前提属性有对应的set/get方法)

1、复杂类型

public class User {
    private int id;
    private String name;
    private String password;
    private Department department;
    private List hobbys;
    private String[] books;
    private Map card;
    private Set games;
    private Properties info;
}


    

    

        

        

        
            
                西游记
                红楼梦
            
        

        
            
                
                
            
        

        
            
                HaHaHa
            
        

        
            
        

        
            
                21219141256
                哈哈哈
                女
            
        
    

5.3 拓展方式注入(使用p和c命名空间注入)

1、头文件加入约束

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

2、注入bean

    

   

3、注意bean中c:和p:注入要和构造器数据对应

4、测试

    @Test
    public void test(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserT user2 = (UserT) context.getBean("papa");
        User user1 = (User) context.getBean("hah");
        System.out.println(user2.getName());
        System.out.println(user1.getName());
    }
6、bean的作用域

1、singleTon(单例模式bean注入默认就是单例模式)

2、原型模式(Protpype 等同于原型设计模式 克隆一个新的属性 hashcode编码不同)

  

3、其余的request、session、application、web开发中用到

7、Bean的自动装配

自动转配是spring满足bean依赖一种方式

spring会在上下文自动寻找,并自动给bean装配属性

装配方式:

1、xml中配置

2、在java中显示配置

3、隐式的自动装配配置

    
        
    




    
        
    

注意事项:

1、byType必须保证全局唯一

2、byName必须和set后面得到名称相同(不区分大小写)

    public void setCaat(Cat cat) {
        this.cat = cat;
    }


    

    
        
    
8、注解自动注入

从jdk1.5和spring2.5才开始支持注解注入

使用须知:

1、导入支持

2、开启自动注入



    
    

1、autowire

直接在属性上添加,或者在set方法上添加

写了autowire我们可以不用写set方法,但必须在spring’容器中提前注入

科普:

@Nullable 字段可以为空 可以再构造器字段前添加

    @Autowired(required = false)//加上required 允许空注入不报错
    @Qualifier(value = "caat")//指定唯一spring中的bena对象创建实例
    private Cat cat;



    @Resource             //首先按照name查找查找到符合的cat的就注入,如果没有就找类型,类型必须唯一不然会报错   按照name匹配是根据对象名去匹配  这里就是caat
    private Cat caat;

    

spring5.0测试结果@Resource和@Autowire 注入原则是一样的先匹配name如果name不合适在匹配类型,如果存在多个类型注入就无法实例化

2、使用注解开发

在spring4之后,要使用注解开发,必须保证aop包的导入,使用注解需要导入context约束,加入注解支持!



    
    
    

1、属性如何注入

@Component
public class People {
    @Value("hello")
    private String name;
    @Autowired
    private Cat cat;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cat getCat() {
        return cat;
    }
   
}

2、衍生的注解

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

1、dao(@Repository)

2、service(@Service)

3、controller(@Controller)

(功能都一样,都是将类注入到容器中)

3、自动装配

@Autowired  自动注入
@Nullable 可以为空null值
@Resource    java自带的注解类 自动注入

4、作用域

@Scope(“”)------>和配置文件中的值一样

5、小结

xml与注解

xml:更加万能,适用于任何场合。

注解:不是自己的类使用不了,维护相对复杂!

重点:所有的实现前提是开启注解支持和有aop jar包支持

9、使用java的方式配置spring

​ xml配置交给java来做,即不用写applicationContext.xml 由 java在创建

JavaConfig 是spring的一个子项目,在spring4之后 ,他成了一个核心功能!

重点:@Configuration本质也是一个bean,

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";

    boolean proxyBeanMethods() default true;
}

列子:

//1、config1
@Configuration
@ComponentScan("pojo")
@Import(config2.class)
public class config1 {

}
//2、config2
@Configuration
@ComponentScan("pojo")
public class config2 {
    @Bean
    public People getPeolpe(){
        return new People();
    }
    @Bean
    public Cat getCat(){
        return new Cat();
    }
}
//entity
@Component
public class People {
    @Value("hello")
    private String name;
    @Autowired
    private Cat cat;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cat getCat() {
        return cat;
    }

}
//Test
public class MyTest {
    @Test
    public void Test01(){
        ApplicationContext context = new AnnotationConfigApplicationContext(config2.class);
        People people = (People) context.getBean("getPeolpe");
        System.out.println(people.getName());
        people.getCat().Catshout();
    }
}
10、代理模式

为什么要学代理模式?因为这就是springAop的底层!【springAop和SpringMvc】

代理模式:

1、静态代理

2、动态地理

1、静态代理

代码步骤:

1、接口

package 静态_代理;

public interface Rent {
    void rent();
}

2、真实角色

package 静态_代理;

public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东出租房子");
    }
}

3、代理角色

package 静态_代理;

public class Proxy implements Rent {
    private Rent rent;

    public Proxy(Rent rent){
        this.rent=rent;
    }
    @Override
    public void rent() {
        seeHose();
        this.rent.rent();
        heTong();
    }

    public void seeHose(){
        System.out.println("中介带你看房子");
    }

    public void heTong(){
        System.out.println("签署租赁合同");
    }
}

4、客户端访问代理角色

package 静态_代理;

public class client {
    public static void main(String[] args) {
        Host host=new Host();
        Proxy proxy=new Proxy(host);

    }
}

代理模式的好处:

1、可以使真实角色的操作更加纯粹!不用关注一些公共的业务

2、公共也就交给代理角色!实现业务的分工1

3、公共业务发生拓展的时候,方便集中管理!

缺点:

一个真实角色需要对应一个代理,开发效率低

2、动态代理

动态代理利用的是反射机制!!!!

动态代理的代理类是动态生成的,不是我们直接写好的!

动态代理分为两大类:1、基于接口的动态代理 2、基于类的动态代理

​ 基于接口:JDK的动态代理

​ 基于类:cglib

​ JAVA字节码实现:javasist

需要两个类:Proxy和InvocationHandler(调用处理程序)

InvocationHandler ----->lang.reflect下的接口

1、接口

package 动态_代理;

public interface Rent {
    void rent();
}

2、真实对象

package 动态_代理;

public class Host implements Rent {
    @Override
    public void rent() {
        System.out.println("房东出租房子");
    }
}

3、代理程序invocationhandler,由他来实例代理对象,并执行方法。

public class ProxyHandler implements InvocationHandler {

    private Rent rent;

    public void setRent(Rent rent){
        this.rent=rent;
    }

    //调用对于方法是都会走invoke来执行,通过获取方法的名字和传入参数的来执行;
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        msg(method.getName());
        Object result=method.invoke(rent,args);
        return result;
    }

    public Object getProxy(){
        return  Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    }

    public void msg(String name){
        System.out.println("执行了"+name+"方法");
    }
}

4、测试

public class Client {
    public static void main(String[] args) {
        Host host=new Host();
        ProxyHandler proxyHandler=new ProxyHandler();
        proxyHandler.setRent(host);
        Rent hhh= (Rent) proxyHandler.getProxy();
        hhh.rent();
    }
}

11、AOP

导包

        
            org.aspectj
            aspectjweaver
            1.9.4
        
一、通过实现接口来添加切面

示例:

1、接口

public interface UserService {
    public void add();
    public void update();
    public void delete();
    public void query();
}

2、实现类

public class UserServiceImpl implements UserService{
    public void add() {
        System.out.println("增加了一个用户");
    }

    public void update() {
        System.out.println("修改了一个用户");
    }

    public void delete() {
        System.out.println("删除了一个用户");
    }

    public void query() {
        System.out.println("查询了一个用户");
    }
}

3、通过实现接口来添加日志信息

public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object returnvalue, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println(method.getName()+"执行了"+"返回结果为:"+returnvalue);
    }
}

4、xml中的配置 添加切入点以及执行通知




    
    
    

    

        

        
        
    

5、测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
        userService.delete();

    }
}

二、自定义切面

1、自定义切面类

package com.huang.diy;

public class diyPointcut {
    public void before(){
        System.out.println("方法执行前!");
    }

    public void after(){
        System.out.println("方法执行后!");
    }
}

2、xml中添加配置

    

        
            
            
            
        
    
三、注解实现

1、编写切面类

package com.huang.annotation;

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 annotationpontCut {
    @Before("execution(* com.huang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }
    @After("execution(* com.huang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执勤后");
    }
    @Around("execution(* com.huang.service.UserServiceImpl.*(..))")
    public void  aroud(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前");
        Signature signature=joinPoint.getSignature();
        System.out.println(signature);
        Object proceed=joinPoint.proceed();
        System.out.println("环绕后");

    }
}

2、xml开启注解支持




    
    
    
    
    
    

    

四、关于execution()

expression=“execution(1.***** 2. com.huang.service.UserServiceImpl.* 3.(…))”

里面的参数 第一个是返回类型 第二个是切入类 第三个是传入参数

12、spring整合Mybatis 一、第一种

1、导包:



    
        spring-learning
        org.example
        1.0-SNAPSHOT
    
    4.0.0

    spring-mybatis
    
     
        
            org.springframework
            spring-jdbc
            5.2.0.RELEASE
        
        
            junit
            junit
            4.12
        
        
            org.aspectj
            aspectjweaver
            1.9.4
        
        
            org.mybatis
            mybatis
            3.5.2
        
        
            org.ehcache
            ehcache
            3.8.1
        
        
            org.mybatis.caches
            mybatis-ehcache
            1.2.1
        
        
            log4j
            log4j
            1.2.17
        
        
            org.mybatis
            mybatis-spring
            2.0.2
        
        
            org.projectlombok
            lombok
            1.18.10
        
        
            mysql
            mysql-connector-java
            5.1.46
        
    
        
            
                src/main/resources
                
                    ***.xml
                
                true
            
            
                src/main/java
                
                    ***.xml
                
                true
            
        
    

    
        UTF-8
    

2、编写实体

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class MyUser implements Serializable {
    private int uid;
    private String u_name;
    private String pwd;
    private int tid;
    //深度克隆
    @Override
    protected MyUser clone() throws CloneNotSupportedException {
        try {
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(bis);
            return  (MyUser)objectInputStream.readObject();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

3、接口

package com.huang.mapper;

import com.huang.pojo.MyUser;

import java.util.List;

public interface userMapper {
    public List selectAllUser();
}

4、接口对应mapper文件






    

5、resource下的mybatis配置文件


        


    
        
    



6、spring和mybatis的关键(把原来需要在mybatis-config.xml中配置的数据写入到spring容器中,并由容器来实例化SqlSessionFactory等对象)





    
        
        
        
        
    

    
        

        

        
    

    

        
    
    
        
    

二、第二种 不需要实例化sqlSessionTemplate 从SqlSessionDaoSupport中获取sqlsession对象

例子:

package com.huang.mapper;

import com.huang.pojo.MyUser;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.dao.support.DaoSupport;

import java.util.List;

public class userMapperImpl2 extends SqlSessionDaoSupport implements userMapper {
    public List selectAllUser() {
        return getSqlSession().getMapper(userMapper.class).selectAllUser();
    }
}

//不在需要实例化sqlSesion直接从父类中去取 简化操作而已

        
 

13、声明事务 1、回顾事务

把一组任务当作一个任务要么成功要么都失败,在项目开发中十分重要确保完整性和一致性。

ACID原则:

1、原子性

2、一致性

3、隔离性:多个业务操作一个资源避免出现数据损坏

4、持久性:一旦提交数据不在受影响

2、spring中的事务管理

1、编程式:AOP

2、声明式:需要在代码中,进行事务管理

声明式:

在配置文件中加载切面类,且切入。

1、不再手写切面类,而是直接再spring容器中注入


    


        
            
            
            
            
            
        
    

    
        
        
    

关于propagation

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

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

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