首页 > 其他分享 >Spring

Spring

时间:2022-11-22 11:23:29浏览次数:54  
标签:www String Spring springframework org public

1、Spring

1.1、简介

  • Spring:春天----》给软件行业带来了春天

  • 2002年,首次推出了Spring框架的雏形:interface21框架

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

  • Rod Johnson是Spring FrameWork创始人,他是学音乐的。

  • spring理念:使现有的技术更容易使用,本身是一个大杂烩,整合了现有的技术框架

  • 解决企业应用开发的复杂性

  • SSH:Struct2+Spring+Hibernate

  • SSM:SpringMVC+Spring+Mybatis

官网:https://repo.spring.io/

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

GitHub地址:

<dependencies>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-webmvc</artifactId>
           <version>5.2.0.RElEASE</version>
       </dependency>

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-jdbc</artifactId>
           <version>5.2.0.RElEASE</version>
       </dependency>
   </dependencies>

1.2、有点

  • Spring是一个开源的免费的框架(容器)

  • Spring是一个轻量级的、非入侵式的框架

  • 控制翻转(IOC),面向切面编程(AOP)

  • 支持事务的处理,对框架整合的支持

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

1.3、组成

image-20221024154456730

 

1.4、拓展

在Spring的官网有这个介绍:现代化的Java开发!就是基于Spring的开发

image-20221024154726921

  • Spring Boot

    • 一个快速开发的脚手架

    • 基于SpringBoot可以快速的开发单个微服务

    • 约定大于配置

  • Spring Cloud

    • SpringCloud是基于SpringBoot实现的

 

2、IOC理论推导

  1. UserDap 接口

  2. UserDaoImpl 实现类

  3. UserService 业务接口

  4. UserServiceImpl 业务实现类

在之前的业务中,用户的需求可能会影响原来的代码,需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本十分昂贵!

image-20221024162047525

 

使用一个Set接口实现

private UserDao userDao;

 //利用set程序进行动态实现值的注入
   public void setUserDao(UserDao userDao) {
       this.userDao = userDao;
  }

 

  • 之前程序是主动创建对象,控制权在程序员手上

  • 使用set注入后,程序不再具有主动性,而是变成了被动的接收对象

这种思想,从本质上解决了问题,程序员不用再去管理对象的创建了。系统的耦合性大大降低,可以更加专注的在业务实现上!这是IOC的原型!

image-20221024162100568

image-20221024162442085

3、HelloSpring

配置文件

<?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="userDaoImpl" class="com.wx.dao.UserDaoImpl"></bean>

   <bean id="mysqlImpl" class="com.wx.dao.UserDaoMysqlImpl"></bean>

   <bean id="oracleImpl" class="com.wx.dao.UserDaoOracleImpl"></bean>



   <bean id="userServiceImpl" class="com.wx.service.UserServiceImpl">
       <!--
       ref: 引用Spring容器中创建好的对象
       value:具体的值
       -->
       <property name="userDao" ref="oracleImpl"/>
   </bean>
</beans>

4、IOC创建对象的方式

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

  2. 假设我们要是用有参构造创建对象

    1. 下标赋值

        <!--通过有参构造方法创建对象,参数通过下标方式传入-->
         <bean id="user1" class="com.wx.pojo.User">
             <constructor-arg index="0" value="王响1"/>
         </bean>
    2. 通过类型

          <!--通过有参构造方法创建对象,参数通过类型方式传入,不建议使用,可能会有通类型的多个参数-->
         <bean id="user2" class="com.wx.pojo.User">
             <constructor-arg type="java.lang.String" value="王响2"/>
         </bean>

       

    3. 通过参数名

      <!--通过有参构造方法创建对象,参数通过参数名方式传入,常用-->
         <bean id="user3" class="com.wx.pojo.User">
             <constructor-arg name="userName" value="王响3"/>
         </bean>

       

    总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!

5、Spring配置

5.1、别名

  <!--别名:可以通过别名获取对象-->
   <alias name="user" alias="wangxiang"/>

5.2、Bean的配置

 <!--
       id:bean的唯一标识符
       class:bean对象所对应的权限定名。包名+类名
       name:别名,name可以同时启多个别名
   -->
   <bean id="user" class="com.wx.pojo.User" name="userA,userB">
       <property name="userName" value="王响"/>
   </bean>

5.3、import

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

假设,项目中有多个人开发,这三个人复制不同 的类开发,不同的类需要注册在不同的bean中,可以利用import将所有人的beans.xml合并为一个总的!

  • 张三

  • 李四

  • 王五

  • applicationContext(总的)

使用的时候直接使用总的配置就可以了

 <import resource="bean1.xml"/>
<import resource="bean2.xml"/>

 

6、DI依赖注入

6.1、构造器注入

 

6.2、Set方式注入(重点)

  • 依赖注入:set注入!

    • 依赖:bean对象的创建依赖于容器

    • 注入:bean对象中所有的属性,由容器来注入

【环境搭建】

  1. 复杂类型

    public class Address {

    private String address;

    public String getAddress() {
    return address;
    }

    public void setAddress(String address) {
    this.address = address;
    }
    }

     

  2. 真实测试对象

    public class Student {

    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> cards;
    private Set<String> games;
    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[] getBooks() {
    return books;
    }

    public void setBooks(String[] books) {
    this.books = books;
    }

    public List<String> getHobbys() {
    return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
    this.hobbys = hobbys;
    }

    public Map<String, String> getCards() {
    return cards;
    }

    public void setCards(Map<String, String> cards) {
    this.cards = cards;
    }

    public Set<String> getGames() {
    return games;
    }

    public void setGames(Set<String> games) {
    this.games = games;
    }

    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 +
    ", books=" + Arrays.toString(books) +
    ", hobbys=" + hobbys +
    ", cards=" + cards +
    ", games=" + games +
    ", wife='" + wife + '\'' +
    ", info=" + info +
    '}';
    }
    }

     

  3. beans.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">

    <!--普通方式注入 value:值-->
    <bean id="student" class="com.wx.pojo.Student">
    <property name="name" value="王响"/>
    </bean>
    </beans>

     

  4. 测试类

    public class MyTest {

    public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Student student = (Student) context.getBean("student");
    System.out.println(student.toString());
    }
    }

完善注入信息

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">


<bean id="student" class="com.wx.pojo.Student">
<!--第一种,普通方式注入 value:值-->
<property name="name" value="王响"/>
<!--第二种,通过Bean的方式注入,ref-->
<property name="address" ref="address"/>
<!--第三种,通过array方式注入-->
<property name="books">
<array>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>

<!--第四种,通过list方式注入-->
<property name="hobbys">
<list>
<value>打篮球</value>
<value>看电影</value>
<value>写代码</value>
</list>
</property>

<!--第五种,通过map方式注入-->
<property name="cards">
<map>
<entry key="身份证" value="1101111111111"></entry>
<entry key="银行卡" value="6281919218929"></entry>
</map>
</property>

<!--第六种,通过set方式注入-->
<property name="games">
<set>
<value>LOL</value>
<value>王者荣耀</value>
</set>
</property>

<!--第六种,null值注入-->
<property name="wife">
<null/>
</property>

<!--第七种,properties方式注入-->
<property name="info">
<props>
<prop key="学号">201122311</prop>
<prop key="名字">小明</prop>
</props>
</property>
</bean>

<bean id="address" class="com.wx.pojo.Address"></bean>
</beans>

 

6.3、拓展方式注入

可以使用p命名空间和c命名空间

<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命名空间注入,可以直接注入属性值-->
<bean id="user" class="com.wx.pojo.User" p:name="王响" p:age="16"></bean>


<!--C命名空间注入,通过构造器注入:construct-args -->
<bean id="user1" class="com.wx.pojo.User" c:age="18" c:name="wangxiang"></bean>

</beans>

测试:

 */
public class MyTest {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml","applicationContext-user.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());

User user = (User) context.getBean("user");
System.out.println(user.toString());

User user1 = (User) context.getBean("user1");
System.out.println(user1.toString());
}
}

p命名空间和c命名空间不能直接使用,需要导入xml约束

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

6.4、bean的作用域

ScopeDescription
singleton(单例) (Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
  • singleton:单例,spring默认,也可以显示的设置

     

    <bean id="user" class="com.wx.pojo.User" p:name="王响" p:age="16" scope="singleton"></bean>
  • 原型模式:每次从容器中get的时候,都会产生一个新的对象

     <bean id="user1" class="com.wx.pojo.User" c:age="18" c:name="wangxiang" scope="prototype"></bean>
  • 其余的request,session,application,websocket这些只能在web开发中使用到

 

7、Bean的自动装配

  • 自动装配是Spring满足bean依赖的一种方式

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

在Spring中有三种装配的方式

  1. 在xml中显示的配置

  2. 在java中显示的配置

  3. 隐式的自动装配【重要】

7.1、环境

环境搭建:一个人有两个宠物

7.2、ByName自动装配

<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
-->
<bean id="person1" class="com.wx.pojo.Person" autowire="byName">
<property name="name" value="王响"></property>
</bean>

7.3、ByType自动装配

 <bean id="dog" class="com.wx.pojo.Dog"></bean>

<bean id="cat" class="com.wx.pojo.Cat"></bean>

<bean id="person" class="com.wx.pojo.Person">
<property name="name" value="王响"></property>
<property name="dog" ref="dog"></property>
<property name="cat" ref="cat"></property>
</bean>

<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
-->
<bean id="person1" class="com.wx.pojo.Person" autowire="byType">
<property name="name" value="王响"></property>
</bean>

 

7.4、使用注解实现自动装配

jdk1.5支持的注解,Spring2.5支持的注解

要使用注解须知:

  1. 导入约束:context约束

  2. 配置注解支持:context:annotation-config/

    <?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>

    @Autowired

    直接在属性上使用即可,也可以在set方法上使用

    使用Autowired可以不用写set方法了,前提是自动装载属性在IOC(spring)容器中存在,且符合名字byname。

    科普:

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

    public @interface Autowired {

    /**
    * Declares whether the annotated dependency is required.
    * <p>Defaults to {@code true}.
    */
    boolean required() default true;

    }
    public class Person {

    private String name;
    //如果现实的定义了Autowired的required属性为false,说明了这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Dog dog;
    @Autowired
    private Cat cat;

    public String getName() {
    return name;
    }

    public Dog getDog() {
    return dog;
    }

    public void setDog(Dog dog) {
    this.dog = dog;
    }

    public Cat getCat() {
    return cat;
    }


    @Override
    public String toString() {
    return "Person{" +
    "name='" + name + '\'' +
    ", dog=" + dog.shout() +
    ", cat=" + cat.shout() +
    '}';
    }
    }

    如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候、我们可以使用@Qualifier(value = "xxx")去配合@Autowired的使用,指定一个唯一的bean对象注入

    public class Person {

    private String name;
    //如果现实的定义了Autowired的required属性为false,说明了这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    @Qualifier(value = "dog")
    private Dog dog;
    @Autowired
    private Cat cat;

    }
    public class Person {

    private String name;
    @Resource(name = "dog")
    private Dog dog;
    @Resource
    private Cat cat;
    }

     

    小结:

    @Resource和@Autowired的区别:

    • 都是用来自动装配的,都可以放在属性字段上

    • @Autowired是通过byType的方式实现的,而且必须要求这个对象存在。【常用】

    • @Resource默认通过byName的方式实现,如果找不到名字,则通过bytype实现。如果两个都找不到就报错。【】常用

    • 执行顺序不同:@Autowired是通过byType的方式实现的,@Resource默认通过byName的方式实现

     

8、使用注解开发

在Spring4之后,要是用注解开发,必须要保证aop的包导入了

image-20221025133715289

使用注解需要导入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>
  • @Component:组件放在类上,说明这个类被Spring管理了,就是Bean

  1. bean

  2. 属性如何注入

    @Component
    public class User {
    //相当于<property name="name" value="wangxiang"/>
    @Value("wangxiang")
    private String name;
    private int age;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }
    }
  3. 衍生的注解

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

    • dao【@Repository】

    • service【@Service】

    • controller【@Controller】

    @Component,@Repository,@Service,@Controller这四个注解功能都是一样的,都是代表将某个类注册到Spring容器中,装配bean。

  4. 自动装配

    @Autowired
  5. 作用域

    @Component
    @Scope("singleton")
    public class User {
    //相当于<property name="name" value="wangxiang"/>
    @Value("wangxiang")
    private String name;
    private int age;

    public String getName() {
    return name;
    }

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

xml与注解:

  • xml更加万能,适用于任何场景!维护更简单

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

最佳实践:

  • xml用来管理bean

  • 注解只负责属性的注入

  • 在使用的过程中,只需要注意一个问题:必须要让注解生效,开启注解支持

 <!--指定要扫描的包路径,这个包下的注解就会生效-->
<context:component-scan base-package="com.wx"/>
<context:annotation-config/>

 

9、使用Java的方式配置Spring

完全不适用Spring的xml配置了,全权交给Java来做。

JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能

image-20221025141335299

/**
* @BelongsProject: wxStuSCB
* @BelongsPackage: com.wx.config
* @Author: wangxiang
* @CreateTime: 2022-10-25 14:09
* @Description: TODO
* @Version: 1.0
* Configuration代表这是一个配置类,相当于applicationContext.xml
*/
@Configuration
@ComponentScan("com.wx")
@Import(MyConfig1.class)

public class MyConfig {

//Bean注册一个bean,相当于之前配置文件中的<bean>标签
//方法名字就相当于配置文件中的id
//返回值就相当于配置文件中class属性
@Bean
public User getUser(){
//返回要注入的对象
return new User();
}
}

测试类

public class MyTest {

public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = (User) context.getBean("getUser");
System.out.println(user.getName());

}
}

 

10、AOP

10.1、什么是AOP

AOP:Aspect Oriented Programming

面向切面编程,通过预编译的方式和运行期动态代理实现程序功能的统一维护的技术。

image-20221025151622728

 

10.2、AOP在Spring中的作用

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

image-20221025151915175

 

10.3、使用Spring实现Aop

 <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>

 

  • 方式一:使用Spring的API接口

     

  • 方式二:使用自定义类来实现

     

  • 方式三:使用注解来实现

 

11、整合Mybatis

步骤:

  1. 导入相关jar包

    1. junit

    2. mybatis

    3. mysql

    4. spring

    5. aop

    6. mybatis-spring

  2. 编写配置文件

  3. 测试

 

Mybatis-Spring

  1. 编写数据源配置

  2. SqlSessionFactory

  3. SQLSessionTemplate

  4. 给接口添加实现类

  5. 将实现类注入到Spring中

  6. 测试

12、声明式事务

  • 把一组业务当成一个业务来做:要么都成功,要么都失败

  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎

  • 确保完整性和一致性

事务ACID原则:

  • 原子性

  • 一致性

  • 隔离性

    多个业务可能操作同一个资源,防止数据损坏

  • 持久性

    事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化到存储器中。

 

Spring中的事务管理

  • 声明式事务

  • 编程式事务

Spring中七种Propagation类的事务属性详解:

REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。

SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。

MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。

REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。

NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。

NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。

标签:www,String,Spring,springframework,org,public
From: https://www.cnblogs.com/wx-36/p/16914549.html

相关文章

  • Springcloud学习笔记52--通过ApplicationContextAware接口从spring上下文中获取到需要
    1.背景在spring项目中,bean之间的依赖关系是spring容器自动管理的,但是一个项目中有些类不在spring容器中却需要使用spring管理的bean,这时候不能通过正常的方式(注解等方式)......
  • 基于Spring-AOP的自定义分片工具
    作者:陈昌浩1背景随着数据量的增长,发现系统在与其他系统交互时,批量接口会出现超时现象,发现原批量接口在实现时,没有做分片处理,当数据过大时或超过其他系统阈值时,就会出现......
  • Spring MVC之Converter类型转换器
    SpringMVC框架的Converter<S,T>是一个可以将一种数据类型转换成另一种数据类型的接口,这里S表示源类型,T表示目标类型。开发者在实际应用中使用框架内置的类型转换器基......
  • Spring Security(2)
    您好,我是湘王,这是我的博客园,欢迎您来,欢迎您再来~ 前面已经把需要的环境准备好了,包括数据库和SQL语句,现在再来写代码。至于安装MySQL什么的就跳过去了,娘度子里面一大把。......
  • Springboot整合Swagger常用注解(三)
    swagger注解主要是用来给swagger生成的接口文档说明用的1、@Api使用范围:用在类上注解,控制整个类生成接口信息的内容,表示对类的说明,也代表了这个类是swagger2的资源参......
  • SpringCloud Gateway 网关常用技术实现
    SpringCloudGateway是目前非常流行的网关中间件,类似于nginx一样,主要提供【路由转发】和【负载均衡】功能,目的是为微服务架构提供一种简单而有效的统一的API路由管理......
  • Spring MVC之Controller参数接收
    @RequestBody接收参数注意事项:@RequestBody:后台接收只能声明一个、且只能接收json@RequestBody:不能和form/data共存@RequestBody:必须是:contentType:"applicatio......
  • spring 源码bean加载过程
    1.xml文件加载#(XmlBeanDefinitionReader)解析spring.xml文件,注册registerBeanDefinitions1.entityResolver->schemaResolver主要加载META-INF/spring.schema......
  • Spring中定时任务@Schedule注解的使用
    概述@Scheduled注解是springboot提供的用于定时任务控制的注解,主要用于控制任务在某个指定时间执行,或者每隔一段时间执行.注意需要配合@EnableScheduling使用,配置@Sch......
  • spring之自定义注解
    @Target({ElementType.METHOD,ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Constraint(validatedBy=MyConstraintValidator.class)public@interface......