Spring学习笔记-01

本文深入解析Spring框架的历史背景、核心理念与组件构成,详细阐述了控制反转(IOC)和依赖注入的基本原理,以及Spring如何通过配置管理Bean,实现对象的创建与装配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Spring

1.1 简介

Maven:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

1.2 优点

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

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

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

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

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

1.3 组成

 

1.4 扩展

Spring官网介绍:现代化的Java开发,说白了就是基于Spring的开发!

  •  Spring Boot:一个快速开发的脚手架,基于SpringBoot可以快速的开发单个微服务,约定大于配置
  • Spring Cloud:是基于SpringBoot实现的

因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC。

弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!”

2、IOC理论推导

1. UserDao接口

public interface UserDao {
    void getUser();
}

2. UserDaoImpl实现类

public class UserDaoImpl implements UserDao {
    @Override
    public void getUser() {
        System.out.println("默认获取用户的数据");
    }
}

3. UserServicie业务接口

public interface UserService {
    void getUser();
}

4. UserServiceImpl业务实现类

public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoOracleImpl();

    @Override
    public void getUser() {
        userDao.getUser();
    }
}

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

我们使用一个set接口实现,已经发生了革命性的变化!

public class UserServiceImpl implements UserService {

    private UserDao userDao;

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

    @Override
    public void getUser() {
        userDao.getUser();
    }
}
  • 之前,程序是主动创建对象,控制权在程序员手上。
  • 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象。

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

IOC本质

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

3、HelloSpring

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 + '\'' +
                '}';
    }
}
<?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">

    <!-- 使用Spirng来创建对象,在Spring中这些都称为Bean

    类型   变量名 = new 类型();
    Hello hello = new Hello();

    id = 变量名
    class = new 的对象
    property 相当于给对象中的属性设置一个值!
     -->
    <bean id="hello" class="com.kuang.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>

</beans>
public class MyTest {
    public static void main(String[] args) {
        // 获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        // 我们的对象现在都在Spring中管理了,我们要使用,直接去里面取出来就可以了。
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

问题:

  • Hello对象由谁创建?--Hello对象由Spring创建
  • Hello对象的属性怎么设置?--Hello对象的属性是有Spring容器设置的

这个过程就叫控制反转;

控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。

反转:程序本身不创建对象,而是变成被动的接收对象。

依赖注入:就是利用set方法来进行注入的。

IOC是一种编程思想,由主动的编程变成被动的接收。

可以通过newClassPathXmlApplicationContext去浏览一下底层源码。

一句话:对象由Spring来创建、管理、装配!

4、IOC创建对象的方式

1. 使用无参构造创建对象,默认!
2. 假设我们要使用有参构造创建对象。

2.1 下标赋值

    <!-- 第一种方式,下标赋值   -->
    <bean id="user" class="com.kaung.pojo.User">
        <constructor-arg index="0" value="旺旺java"/>
    </bean>

2.2 类型

    <!-- 第二种方式,通过类型创建。不建议使用,如果两个参数都是String,就会出现问题   -->
    <bean id="user" class="com.kaung.pojo.User">
        <constructor-arg type="java.lang.String" value="wangjie"/>
    </bean>

2.3 参数名

    <!-- 第三种方式,直接通过参数名来设置   -->
    <bean id="user" class="com.kaung.pojo.User">
        <constructor-arg name="name" value="旺旺"/>
    </bean>

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

5、Spring配置

5.1 别名

    <!--别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
    <alias name="user" alias="userNew"/>

5.2 Bean的配置

     <!--
     id:bean 的唯一标识符,也就是相当于我们学的对象名
     class:bean 对象所对应的全限定名:包名 + 类型
     name:也是别名,而且name可以同时取多个别名
     -->
    <bean id="userT" class="com.kaung.pojo.UserT" name="user2 u2,u3;u4">
        <property name="name" value="南部封闭"/>
    </bean>

5.3 import

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

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

applicationContext.xml

<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>

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

6、依赖注入

6.1 构造器注入

 

6.2 Set方式注入【重点】

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

【环境搭建】

1. 复杂类型

public class Address {
    private String addresss;

    public String getAddresss() {
        return addresss;
    }

    public void setAddresss(String addresss) {
        this.addresss = addresss;
    }
}

2. 真实测试对象

public class Student {
    private String name;
    private Address address;
    private  String[] books;
    private List<String> hobbies;
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
}

3. beans.xml

<?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="student" class="com.kuang.pojo.Student">
    <!-- 第一种,普通值注入,value -->
        <property name="name" value="旺旺"/>
    </bean>

</beans>

4. 测试类

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

完善注入信息

<?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="address" class="com.kuang.pojo.Address">
        <property name="addresss" value="苏州"/>
    </bean>

    <bean id="student" class="com.kuang.pojo.Student">
        <!-- 第一种,普通值注入,value -->
        <property name="name" value="旺旺"/>

        <!-- 第二种,Bean注入,ref -->
        <property name="address" ref="address"/>

        <!-- 数组 -->
        <property name="books" >
            <array>
                <value>红楼梦</value>
                <value>水浒传</value>
                <value>西游记</value>
                <value>三国演义</value>
            </array>
        </property>

        <!--List-->
        <property name="hobbies">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>

        <!-- Map -->
        <property name="card">
            <map>
                <entry key="身份证" value="1111111111"/>
                <entry key="银行卡" value="68907687898"/>
            </map>
        </property>

        <!-- Set -->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>

        <!-- null -->
        <property name="wife">
            <null/>
        </property>

        <!-- Properties -->
        <property name="info">
            <props>
                <prop key="driver">20190525</prop>
                <prop key="url">男</prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>

            </props>
        </property>

    </bean>

</beans>

 

6.3 扩展方式注入

我们可以使用p命名空间和c命名空间进行注入

官方解释:

使用:

<?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: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命名空面注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.kuang.pojo.User" p:name="旺旺" p:age="18"/>

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

</beans>

测试:

    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user2", User.class);
        System.out.println(user);
    }

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

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

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

6.4 bean的作用域

1. 单例模式(Spring默认机制)

<bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="wonjack" scope="singleton"/>

singleton

2. 原型模式:每次从容器中get的时候,都会产生一个新对象。

<bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="wonjack" scope="prototype"/>

prototype

3. 其余的:request、session、application这些只能在web开发中使用到!

7、Bean的自动装配

  • 自动装配是Spring满足bean依赖的一种方式!
  • Spring会在上下文中寻找,并自动给bean装配属性。

在Spring中有三种装配的方式:

  1. 在xml中显式的配置
  2. 在Java中显式配置
  3. 隐式的自动装配bean【重要】

7.1 测试

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

 

7.2 ByName自动装配

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

7.3 ByType自动装配

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

小结:

  • ByName时:需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
  • ByType时:需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致。

7.4 使用注解实现自动装配

jdk1.5支持注解,Spring2.5就支持注解了。

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML. 

要使用注解须知:

  1. 导入约束:context约束
  2. 配置注解的支持 
<?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 {
    boolean required() default true;
}

测试代码:

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

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

    @Autowired
    @Qualifier(value = "cat111")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;

@Resource注解

public class People {
    @Resource(name = "cat1")
    private Cat cat;

    @Resource
    private Dog dog;
    private String name;
}

 小结:

@Resource和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired通过ByType的方式实现,而且必须要求这个对象存在!【常用】
  • @Resource默认通过ByName的方式实现,如果找不到名字,则通过ByType实现。如果两个都找不到的情况下,就报错!【常用】
  • 执行顺序不同:@Autowired通过ByType的方式实现;@Resource默认通过ByName的方式实现;

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值