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

【学习笔记02】Spring

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

【学习笔记02】Spring

Spring 一、前置工作与Spring简介

使用Spring只需要在项目中导入包即可:


    org.springframework
    spring-webmvc
    5.2.0.RELEASE


后期要和mybatis整合时还可以再导入另一个包:

        
        
            org.springframework
            spring-jdbc
            5.2.0.RELEASE
        

Spring的优点

Spring是一个开源的免费框架(容器)Spring是一个轻量级的,非侵入式的框架控制反转(IOC),面向切面编程(AOP)支持事务的处理,支持框架整合

spring就是一个控制反转(IOC)和面向切面编程(AOP)的轻量级框架

二、关于控制反转IOC

参考大佬博客

三、第一个Spring程序HelloSpring

1.先在resourses目录下创建Spring的配置文件,如Beans.xml,并写入:



	



2.创建实体类(一定要有无参构造方法并为每一个属性设定get和set方法),以Hello实体类为例:

 private String str;
    public Hello() {
    }

    public Hello(String str) {
        this.str = str;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + ''' +
                '}';
    }

3.在步骤一创建的配置文件中映射实体类

    

4.使用实体类

    @Test
    public void HelloSpring() {
        //先读取配置文件(此语句格式固定,可一次读取多个配置文件)
        ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
        //通过context取代new创建对象 
        Hello hello = (Hello) context.getBean("hello");
        //正常使用该对象
        System.out.println(hello.toString());
    }

这样创建默认使用的是无参构造再去调用属性的set方法,想要使用有参构造,可以这样配置:

    

    

或者:

    
        
    
四、Spring配置

1.alias别名

​ 用于给Spring配置的bean标签id起别名


2.import导入

​ 一般用于团队开发,可以将多个配置文件合并成为一个总的配置文件


五、依赖注入 1.普通值注入

​ 直接在bean标签中使用property标签中的name和value注入即可

2.复杂类型注入

首先搭建复杂类型环境:

//学生类
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List hobbys;
    private Map card;
    private Set games;
    private String wife;
    private Properties info;
}
=======两个类不在同一包中且省略了get/set方法和构造器=======

//地址类
public class Address {
    private String address;
}

name属性属于普通值注入,使用value注入即可,剩下的类型我们一个一个看。

① 一个类中存在另一个实体类 Address

​ 这里需要再注册Address类并在Student类的注册中使用ref注入

    
        
    

    
        
    
② 数组注入 String[]

​ 在property标签内部在使用array标签配置

        
            
                童话书
                教科书
            
        

③集合注入List

​ 在property标签内部使用list标签配置

        
            
                听歌
                看电影
                吃饭
            
        

④Map注入

​ 在property标签内部使用map标签且在map内使用entry赋值注入

        
            
                
                
            
        

⑤set注入

​ 在property标签内部使用set标签配置

        
            
                lol
                coc
                bob
            
        

⑥null值注入

​ 在property标签内部使用null标签注入

        
            
        

⑦Properties类注入

        
            
                root
                123456
            
        
六、Bean的作用域

Bean的作用域可以在property标签内通过scope属性配置,Bean的作用域有六种:

1.singleton单例模式
- 单例是Spring中Bean的默认作用域即不设置scope属性的Bean作用域就是singleton
- 单例模式下所有创建出来的对象实际上为同一个对象
2.prototype原型模式

原型模式下每次创建出来的对象都为一个新的对象 3.request,session,application

只有在web开发中用到,跟web中的作用域一样 七、Bean的自动装配

Spring可以在上下文中自动寻找并自动给bean装配属性。

Spring中有三种装配的方式:

​ 1.在xml中手动显示的配置

​ 2.在java中手动显示的配置

​ 3.隐式的自动装配

1.byName自动装配

people类中存在Dog和Cat类

byName会在容器上下文中自动查找和自己set参数名字相同的id并注入

    
    
    
        
    
2.byType自动装配

byType会在容器上下文中自动查找和自己对象属性类型相同的bean并注入

    
    
    
        
    

注意点:byType必须保证被匹配的bean类型全局唯一

3.使用注解自动装配

使用注解开发前首先需要导入注解的配置(即包含context命名空间)




    


在定义实体类中将需要自动装配的属性/set方法上添加@autowired注解

public class people{
    private String name;
    @autowired
	private Cat cat;
    private Dog dog;
    @autowired
    public getDog(Dog dog){
        this.dog = dog;
    }
    
}

使用@autowired注解自动装配本质还是使用的byType,找不到使用byName。所以需要保证自动装配的对象在ioc容器中存在且唯一。

@autowired还存在一个属性required,默认为true,我们可以把它改成false,这时这个属性可以为null,否则不能为null。

@autowired(required = false)
private Cat cat;

当ioc容器中存在多个与之匹配的类型时,我们还可以使用@Qualifier显示使用byName匹配注入的值

@autowired(required = false)
@Qualifier(value = "cat2")
private Cat cat;

@Resource注解,类似autowired注解,默认使用byName,找不到使用byType,略

八、注解开发 前置工作

1.使用注解开发必须保证AOP的包已经导入了(在最开始导入mvc包时已导入该包)

2.使用注解必须导入context约束,增加注解的支持并指定要扫描的包。




    
    
    
    
    


常用注解

    @Conponent 组件(用在类上)

    说明这个类被Spring管理了,注册了bean

    import org.springframework.stereotype.Component;
    //等价于
    @Component
    public class User {
    }
    

    @Value(用在属性上)

    为该属性注入值

        @Value("刘博")
        public String name;
    

3.@Conponent衍生注解

​ 在web开发中按照mvc三层架构开发的思想,以下注解均和@Conponent作用相同,但我们用于不同的地方

​ Dao — @Repository

​ Service — @Service

​ Controller — @Controller

​ 注意点:一定要记得注释装配后还要在核心配置文件中设定扫描这些包

4.@Scope作用域

​ 通过该注释修改注册的bean的作用域

@Scope("singleton");
@Scope("prototype");
九、使用java类取代配置文件

新建一个java类,如TuanConfig

使用@Configuration注解标识这个类为核心配置类;

使用@ComponentScan(“com.tuan.pojo”)扫描一个包;

使用@Bean表示注册一个类;

import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.tuan.pojo")
public class TuanConfig {
    @Bean
    public User getUser() {
        return new User();
    }
}

现在在使用中需要这样得到配置好的类的对象:

区别:

​ 1. 我们现在通过的是AnnotationConfigApplicationContext()类来得到ApplicationContext对象,参数为配置类的class;

​ 2. getBean的参数为配置类中注册时的方法名而不是注册的对象名,或者注册时使用@bean中的参数指定id

    @Test
    public void userText() {
        ApplicationContext context = new AnnotationConfigApplicationContext(TuanConfig.class);
        User user =(User) context.getBean("getUser");
        user.setName("123");
        System.out.println(user.getName());
    }
十、AOP

使用Spring实现AOP

前提还是需要在配置文件中设置aop命名空间




导入aop植入包:

        
            org.aspectj
            aspectjweaver
            1.9.4
        

方式一:

原生配置

log和aftlog分别是实现了BeforeAdvice和AfterReturningAdvice的类

execution(修饰符 返回值 包名.类名/接口名.方法名(参数列表))注意老师忽略掉修饰符了 自己可以写上修饰符试试
(…)可以代表所有参数,()代表一个参数,(,String)代表第一个参数为任何值,第二个参数为String类型.

方式二:

自定义一个类代表类 我们可以在配置中引入切面

这是我们的自定义类,里面只有两个方法, 我们要把这两个方法植入到另一个类中的所有方法的执行前后

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s1ep0ylB-1647414402800)(Spring.assets/image-20211114001725603.png)]

下面是配置

方式三:使用注解实现

使用注解前需要开启注解支持


十一、整合mybatis

还是提前引入依赖。

需要的依赖有:

        
        
            org.springframework
            spring-webmvc
            5.2.0.RELEASE
        
    
    
        org.springframework
        spring-jdbc
        5.2.0.RELEASE
    
        
            junit
            junit
            4.12
        
        
            org.aspectj
            aspectjweaver
            1.9.4
        
        
        
            org.mybatis
            mybatis
            3.5.7
        

        
        
            org.mybatis
            mybatis-spring
            2.0.6
        

        
        
            mysql
            mysql-connector-java
            8.0.27
        

编写数据库对应的实体类,实体类的mapper接口,接口对应的xml接口和接口的实现类

//接口
public interface UserMapper {
    List selectUser();
}

//接口实现类public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;

    public SqlSessionTemplate getSqlSession() {
        return sqlSession;
    }

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List users = mapper.selectUser();
        return users;

    }
}
public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;

    public SqlSessionTemplate getSqlSession() {
        return sqlSession;
    }

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List users = mapper.selectUser();
        return users;

    }
}

//xml对应配置文件




    

第一种整合方式

然后需要在Spring中注册以下Spring内置的实体类:

    
        
        
        
        
    

    
        

        


        

    

    
        
    

    
        
    

最后java中这样使用mybatis

        ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = (UserMapperImpl)context.getBean("userMapper");
        List users = userMapper.selectUser();
第二种整合方式

接口实现类再继承SqlSessionDaoSupport接口可以不用注册直接调用 getSqlSession方法获取 sqlsession

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper  {

    @Override
    public List selectUser() {
        return this.getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

Spring中的事务管理

要开启事务管理,需在Spring中创建DataSourceTransactionManager对象配置声明式事务

    
        
    

然后配置事务通知(记得开启tx命名空间):

    
        
            
            
            
            
            
        
    

最后配置事务利用aop切入:

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

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

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