Spring:Bean

news2024/9/29 9:23:58

Bean

  • 概述
    • 配置方式
    • 自动装配
    • 继承与依赖
    • 作用域
    • 外部属性文件的使用

在这里插入图片描述

概述

Spring 容器负责管理依赖注入,它将被管理的对象都称为 bean 。我们通过 xml 文件配置方式进行对 bean 的声明和管理。

写法如下:

<beans>
    <bean id="bean的唯一标识符" class="对应bean的全路径类名">
        <!-- Setter注入标签,进行对象属性赋值 -->
        <property />
        <!-- 构造器注入标签,进行对象属性赋值 -->
        <constructor-arg />
    </bean>
</beans>

获取 Spring 配置文件:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("配置文件1.xml","配置文件2.xml"...);
//通过 getBean() 获取容器中的对象实例,一般使用 getBean("id")

配置方式

下面简单介绍 Bean 配置 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"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

    <!-- property标签的value/ref属性写法 -->
    <!-- <bean id="admin" class="cn.edu.springdemo.model.Admin"> -->
        <!-- 第一种写法 -->
        <!-- <property name="username" value="admin" /> -->
        <!-- 第二种写法 -->
        <!-- <property name="password"> -->
            <!-- 另外,当其value属性值使用特殊字符(如:<>),需要在这个写法下利用<![CDATA[value值]]> -->
            <!-- <value><![CDATA[<admin>]]></value> -->
        <!-- </property> -->
        <!-- 引用 -->
        <!-- <property name="map" ref="CommonMap" /> -->
        <!-- <property name="set" ref="CommonSet" /> -->
        <!-- <property name="list" ref="CommonList" /> -->
    <!-- </bean> -->

    <!-- 独立配置集合bean(如map、set、list等),方便重复引用 -->
    <util:map id="CommonMap">
        <entry key="曹操" value="20230408"></entry>
        <entry key="刘备" value="20230409"></entry>
        <entry key="孙权" value="20230410"></entry>
    </util:map>

    <util:set id="CommonSet">
        <value></value>
        <value></value>
        <value></value>
    </util:set>

    <util:list id="CommonList">
        <value>15936287401</value>
        <value>15936287402</value>
        <value>15936287403</value>
    </util:list>

    <!-- 使用p命名空间简化bean的配置(与注释的配置一样的效果) -->
    <bean id="admin" class="cn.edu.springdemo.model.Admin"
          p:username="admin" p:password="admin"
          p:map-ref="CommonMap" p:set-ref="CommonSet" p:list-ref="CommonList" />
</beans>

自动装配

自动装配(AutoWiring),指 Spring 可以自动向 Bean 注入依赖。其中使用自动装配需要配置 bean 标签的 autowire 属性,属性值主要有 no(不使用自动装配)、byType 、byName 、constructor 。

创建三个实体类:

package cn.edu.springdemo.beanDemo;

//学科类
public class Discipline {
    private int id;
    private String discipline;

    public int getId() {
        return id;
    }

    public String getDiscipline() {
        return discipline;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setDiscipline(String discipline) {
        this.discipline = discipline;
    }

    @Override
    public String toString() {
        return "Discipline{" +
                "id=" + id +
                ", discipline='" + discipline + '\'' +
                '}';
    }
}
package cn.edu.springdemo.beanDemo;

//成绩类
public class Score {
    private int id;
    private int score;

    public int getId() {
        return id;
    }

    public int getScore() {
        return score;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setScore(int score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Score{" +
                "id=" + id +
                ", score=" + score +
                '}';
    }
}
package cn.edu.springdemo.beanDemo;

import java.util.List;

//学生类
public class Student {
    private int id;
    private String name;
    private Discipline discipline;
    private List<Score> scores;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Discipline getDiscipline() {
        return discipline;
    }

    public List<Score> getScores() {
        return scores;
    }

    public void setId(int id) {
        this.id = id;
    }

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

    public void setDiscipline(Discipline discipline) {
        this.discipline = discipline;
    }

    public void setScores(List<Score> scores) {
        this.scores = scores;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", discipline=" + discipline +
                ", scores=" + scores +
                '}';
    }
}

创建测试结果的类:

package cn.edu.springdemo.test;

import cn.edu.springdemo.beanDemo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//测试类
public class AdminTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanDemo.xml");
        Student student = (Student) applicationContext.getBean("student");
        System.out.println(student);
    }
}

1. xml 文件配置:自动装配使用 byType 属性值时,将会根据该 bean 的属性类型来匹配容器中对应类型的 bean 进行自动注入,同时必须要有 Setter 方法。

<?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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

	<!-- Discipline 类的对象属性值将会自动注入在 id 为 student 的 bean 上 -->
    <bean id="discipline1" class="cn.edu.springdemo.beanDemo.Discipline" p:id="1" p:discipline="数学" />

	<!-- 给 Score 类的对象属性赋值 -->
    <bean id="math" class="cn.edu.springdemo.beanDemo.Score" p:id="1" p:score="96" />

	<!-- 获取 id="math" 的 bean 后将会自动注入在 id="student" 的 bean 上 -->
    <util:list id="scores">
        <ref bean="math" />
    </util:list>

	<!-- Student 类属性类型有 int、String、Discipline、List<Score> 类型,其中 Discipline、List<Score> 类型自动装配 -->
    <bean id="student" class="cn.edu.springdemo.beanDemo.Student" p:id="20230416" p:name="曹操" autowire="byType" />
</beans>

结果如图:
在这里插入图片描述

注: 当存在多个相同类但不同的 bean 实例时,需要在 bean 标签中使用 autowire-candidate=“false” 来指定不需要注入的 bean 实例

2. xml 文件配置:自动装配使用 byName 属性值时,将会根据该 bean 的属性名来匹配容器中对应 bean 名的 bean 进行自动注入。

<?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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

    <!-- id="discipline"的 bean 与 Student 类 Discipline 属性的名称一致,会自动注入在 id 为 student 的 bean 上  -->
    <bean id="discipline" class="cn.edu.springdemo.beanDemo.Discipline" p:id="1" p:discipline="数学" />
    <!-- 名字不匹配,不会注入 -->
    <bean id="discipline2" autowire-candidate="false" class="cn.edu.springdemo.beanDemo.Discipline" p:id="2" p:discipline="英语" />

    <!-- 给 Score 类的对象属性赋值 -->
    <bean id="math" class="cn.edu.springdemo.beanDemo.Score" p:id="1" p:score="96" />
    <bean id="english" class="cn.edu.springdemo.beanDemo.Score" p:id="2" p:score="98" />

    <!-- 获取 Score 类对象属性值,id="scores" 与 Student 类 List<Score> 属性的名称一致,会自动注入在 id 为 student 的 bean 上 -->
    <util:list id="scores">
        <ref bean="math" />
        <ref bean="english" />
    </util:list>

    <!-- Student 类属性类型有 int、String、Discipline、List<Score> 类型,其中 Discipline、List<Score> 类型使用自动装配 -->
    <bean id="student" class="cn.edu.springdemo.beanDemo.Student" p:id="20230416" p:name="曹操" autowire="byName" />
</beans>

结果如图:
在这里插入图片描述

3. 自动装配使用 constructor 属性值时,将会根据该 bean 的构造器参数类型来匹配容器中对应类型的 bean 进行自动注入。与 byType 类似,都通过类型来匹配,但区别在于 byType 需要 Setter 方法,而 constructor 需要构造方法。所以,这使得更复杂,简单认识,不推荐使用。

继承与依赖

Bean 的继承是 bean 配置项之间的继承关系。子bean 必须有 父bean 定义的所有属性,子bean 可以继承或覆盖 父bean 的属性;父bean 可以作为配置模板或 bean 实例 。

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Bean继承 -->
    <!-- 父bean设置为配置模板,需要在 abstract 属性中设置为 true 值 -->
    <bean abstract="true" id="father" class="cn.edu.springdemo.beanDemo.Father" p:name="刘备" p:sex="" p:bloodType="O型血" p:eyelidType="双眼皮" />
    <!-- 子bean 继承 父bean ,需要在 parent 属性中设置为 父bean 的 id 值 -->
    <bean parent="father" id="son" class="cn.edu.springdemo.beanDemo.Son" p:name="刘禅" />

</beans>

测试结果:父bean 为配置模板,不被实例化,不能获取;子bean 覆盖了 父bean 的 name 属性,继承了其他属性,如图:
在这里插入图片描述

Bean 的依赖 是 通过 bean 标签的 depends-on 属性来确定一个 bean 依赖另一个 bean,进而实现 bean 实例化的先后顺序。即当 A 依赖 B 时,在 A 实例化前,B 已经实例化。若 B 没有实例化,A 无法实例化,Spring 容器会报错。

<!-- Bean依赖 -->
<!-- 当依赖多个 bean 的时候,使用逗号或空格隔开 -->
<bean depends-on=" 前置依赖 Bean " />
注:B 为前置依赖 Bean

作用域

Bean 的作用域是通过 bean 标签中的 scope 属性来设定 Bean 实例的作用范围。属性值主要有 singleton、prototype、request、session、global-session 。

属性值作用
singleton默认值,每次从容器中获取的实例都是同一个实例
prototype每次从容器中获取的实例都会重新创建
request只作用于HTTP请求,每次HTTP请求从容器中获取的实例都会重新创建
session只作用于HTTP Session,但不同的Session从容器中获取的实例不同
global-session只作用于HTTP Session,每次从容器中获取的实例都是同一个实例

外部属性文件的使用

引用外部属性文件是将 bean 的配置信息提取到 bean 配置文件的外部,以 properties 格式文件保存,并在 bean 配置文件中通过 ${key} 的方式引用属性文件中的属性项。这样,更便于部署和维护。

简单示例:

首先在 pom.xml 中添加两个依赖:

<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
</dependency>

然后在 resources 目录下创建 jdbc.properties ,添加以下内容:

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC
jdbc.user=root
jdbc.password=0123

接着在 beanDemo.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 使用context命名空间,通过 location 属性指定 properties 文件位置 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
</beans>

最后,测试结果:

package cn.edu.springdemo.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.SQLException;

public class JDBCUtilTest {
    public static void main(String[] args) throws SQLException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanDemo.xml");
        DataSource dataSource = (DataSource) applicationContext.getBean("dataSource");
        System.out.println(dataSource.getConnection());
    }
}

结果如图:
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/711692.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Scrapy框架--CrawlSpider (详解+例子)

目录 CrawlSpider 简介 基本运行 特性和概念 基本使用 创建CrawlSpider 运行 使用CrawlSpider中核心的2个类对象 Rule对象 LinkExtractors 作用 使用 查看效果-shell中验证 示例 注意 CrawlSpider 简介 CrawlSpider 是 Scrapy 框架提供的一个特殊的 Spider 类…

Jvm内存模型剖析优化-JVM(四)

上篇文章代码实例详解如何自定义双亲委派&#xff0c;主要实现ClassLoader&#xff0c;有两个方法&#xff0c;一个直接loadClass用父类的&#xff0c;如果想在破坏&#xff0c;则需要重写loadClass&#xff0c;一个findClass必须要重新&#xff0c;因为父类是空的&#xff0c;…

SpringBoot3之GraalVM之Linux详细安装及使用教程

Linux安装底层工具相关依赖 yum install -y gcc glibc-devel zlib-devel安装GraalVM JDK 《GraalVM官网下载》 找到最近的GraalVM Community Edition X.X.X点击Assets&#xff08;因为我的是SpringBoot3项目&#xff0c;起始JDK就要求17&#xff0c;所以我下载17&#xff09;下…

青少年机器人技术一级核心知识点:机械结构及模型(一)

随着科技的不断进步&#xff0c;机器人技术已经成为了一个重要的领域。在这个领域中&#xff0c;机械结构是机器人设计中至关重要的一部分&#xff0c;它决定了机器人的形态、运动方式和工作效率。对于青少年机器人爱好者来说&#xff0c;了解机械结构的基础知识&#xff0c;掌…

vim背景颜色设置

cd ~进入个人家目录下&#xff0c;vim .vimrc进入vimrc文件&#xff1a; 在主题设置部分对颜色背景进行设置&#xff0c;onedark表示黑色背景&#xff0c;default表示白色背景&#xff0c;按需设置即可&#xff01;

网络知识点-链路聚合

链路聚合&#xff08;英语&#xff1a;Link Aggregation&#xff09;是一个计算机网络术语&#xff0c;指将多个物理端口汇聚在一起&#xff0c;形成一个逻辑端口&#xff0c;以实现出/入流量吞吐量在各成员端口的负荷分担&#xff0c;交换机根据用户配置的端口负荷分担策略决定…

【数据结构】算法的时间和空间复杂度

目录 1.什么是算法&#xff1f; 1.1算法的复杂度 2.算法的时间复杂度 2.1 时间复杂度的概念 计算Func1中count语句总共执行了多少次 2.2 大O的渐进表示法 2.3常见时间复杂度计算举例 实例1:执行2N10次 实例2:执行MN次 实例3:执行了100000000次 实例4:计算strchr的时…

java jwt生成token并在网关设置全局过滤器进行token的校验并在给请求头设置参数及在微服务中解析参数

1、首先引入jjwt的依赖 <dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version> </dependency>2、编写生成token的工具类 package com.jjw.result.util;import com.jjw.res…

软考高级系统架构设计师(九) 作文模板-论设计模式及其应用(未完待续)

目录 掌握的知识点 创建型 结构型 行为型 掌握的知识点 设计模式分为哪3类 每一类包含哪些具体的设计模式 创建型 创建型模式是对对象实例化过程的抽象&#xff0c;他通过抽象类所定义的接口&#xff0c;封装了系统中对象如何创建、组合等信息。 创建型模式主要用于创建对…

【物联网】微信小程序接入阿里云物联网平台

微信小程序接入阿里云物联网平台 一 阿里云平台端 1.登录阿里云 阿里云物联网平台 点击进入公共实例&#xff0c;之前没有的点进去申请 2.点击产品&#xff0c;创建产品 3.产品名称自定义&#xff0c;按项目选择类型&#xff0c;节点类型选择之恋设备&#xff0c;联网方式W…

Linux下安装Redis的详细安装步骤

一.Redis安装 1.下载linux压缩包 【redis-5.0.5.tar.gz】 2.通过FlashFXP把压缩包传送到服务器 3.解压缩 tar -zxvf redis-5.0.5.tar.gz4.进入redis-5.0.5可以看到redis的配置文件redis.conf 5.基本的环境安装 使用gcc -v 命令查看gcc版本已经是4.8.5了&#xff0c;于是就…

ubuntu系统突然失去网络问题

修复ubuntu系统网络问题 1. 服务不存在&#xff1f;2. 修改配置&#xff0c;自动启动网络 每天都在用的ubuntu系统突然ssh连接不上&#xff0c;进系统ifconfig也不显示ip。当然也ping不通任何网页。 1. 服务不存在&#xff1f; 初步怀疑网络服务被关闭了&#xff0c;需要修改配…

【C6】数据类型/移植/对齐,内核中断,通过IO内存访问外设,PCI

文章目录 1.内核基础数据类型/移植性/数据对齐&#xff1a;页大小为PAGE_SIZE&#xff0c;不要假设4K&#xff0c;保证可移植性1.1 kdatasize.c&#xff1a;不同的架构&#xff08;x86_64,arm&#xff09;&#xff0c;基础类型大小可能不同&#xff0c;主要区别在long和指针1.2…

chatgpt赋能python:用Python访问数据库的SEO文章

用Python访问数据库的SEO文章 在当今互联网飞速发展的时代&#xff0c;数据处理和数据库技术的重要性不言而喻。在这些应用中&#xff0c;Python是使用最广泛和最受欢迎的编程语言之一。Python的简单和易学性使其成为理想的选项&#xff0c;可以通过Python来访问各种类型的数据…

荣耀90推出最新MagicOS7.1更新,增加控制中心功能

荣耀 90 系列机型推出了最新的 Magic OS 7.1更新&#xff0c;版本号为7.1.0.137 (C00E130R2P2)。该更新主要增加了控制中心功能&#xff0c;并对部分场景拍摄效果进行了优化。此外&#xff0c;该更新还提升了系统与部分三方应用的兼容性&#xff0c;以提高系统性能和稳定性。 …

选择最适合您自动化系统的控制方式

自动化系统可采用多种不同的控制方式&#xff0c;其中硬件控制和PLC&#xff08;可编程逻辑控制器&#xff09;是常见的选择。 刚好&#xff0c;我这里有上位机入门&#xff0c;学习线路图&#xff0c;各种项目&#xff0c;需要留个6。 硬件控制通常指使用专用硬件电路实现控…

C++3(sizeof和逗号运算符,类型转换)

1.sizeof的用法 逗号运算符 口诀&#xff1a;从左到右算&#xff0c;返回最右边的值 类型转换 如何实现的隐式类型转换&#xff1f; 先算右边的&#xff0c;右边的3&#xff08;int&#xff09;先提升为double &#xff0c;然后算得&#xff08;7.541&#xff08;double&#…

CMU 15-445 -- 关系型数据库重点概念回顾 - 01

CMU 15-445 -- 关系型数据库重点概念回顾 - 01 引言Relational Data ModelDBMS数据模型Relational ModelRelation & TuplePrimary KeysForeign Keys Data Manipulation Languages (DML)Relational Algebra Advanced SQLSQL 的历史SQLAggregatesGroup ByHavingOutput Redire…

内存屏障类型表

load store 啥意思 内存屏障类型表 StoreLoad Barriers是一个“全能型”的屏障&#xff0c;它同时具有其他3个屏障的效果。现代的多处理器大多支持该屏障&#xff08;其他类型的屏障不一定被所有处理器支持&#xff09;。执行该屏障开销会很昂贵&#xff0c;因为当前处理器通常…

在文件每行开头或结尾插入指定字符

1、在文件每行插入指定字符 sed -i "s/^/curl /g" missing.txt效果 2、在每行末尾插入指定字符 sed -i "s/$/结束 /g" missing.txt