首页 > 其他分享 >5. IOC DI配置管理第三方bean

5. IOC DI配置管理第三方bean

时间:2023-06-23 21:34:16浏览次数:34  
标签:xml jdbc 配置文件 配置管理 bean IOC properties 加载

1.1 案例:数据源对象管理

在这一节中,我们将通过一个案例来学习下对于第三方 bean 该如何进行配置管理。

以后我们会用到很多第三方的 bean,本次案例将使用咱们前面提到过的数据源Druid(德鲁伊)​ 和C3P0​ 来配置学习下。

1.1.1 环境准备

学习之前,先来准备下案例环境:

  • 创建一个 Maven 项目

  • pom.xml 添加依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
    </dependencies>
    
  • resources 下添加 spring 的配置文件 applicationContext.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
                http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    </beans>
    
  • 编写一个运行类 App

    public class App {
        public static void main(String[] args) {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        }
    }
    

1.1.2 思路分析

在上述环境下,我们来对数据源进行配置管理,先来分析下思路:

需求:使用 Spring 的 IOC 容器来管理 Druid 连接池对象

1.使用第三方的技术,需要在 pom.xml 添加依赖

2.在配置文件中将【第三方的类】制作成一个 bean,让 IOC 容器进行管理

3.数据库连接需要基础的四要素驱动​、连接​、用户名​ 和密码​,【如何注入】到对应的 bean 中

4.从 IOC 容器中获取对应的 bean 对象,将其打印到控制台查看结果

思考:

  • 第三方的类指的是什么?
  • 如何注入数据库连接四要素?

1.1.3 实现 Druid 管理

带着这两个问题,把下面的案例实现下:

步骤 1:导入druid​ 的依赖

pom.xml 中添加依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.16</version>
</dependency>
步骤 2:配置第三方 bean

在 applicationContext.xml 配置文件中添加DruidDataSource​ 的配置

<?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
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--管理DruidDataSource对象-->
    <bean class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_db"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
</beans>

说明:

  • driverClassName:数据库驱动
  • url:数据库连接地址
  • username:数据库连接用户名
  • password:数据库连接密码
  • 数据库连接的四要素要和自己使用的数据库信息一致。
步骤 3:从 IOC 容器中获取对应的 bean 对象
public class App {
    public static void main(String[] args) {
       ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
       DataSource dataSource = (DataSource) ctx.getBean("dataSource");
       System.out.println(dataSource);
    }
}
步骤 4:运行程序

打印如下结果: 说明第三方 bean 对象已经被 spring 的 IOC 容器进行管理

​​image​​

做完案例后,我们可以将刚才思考的两个问题答案说下:

  • 第三方的类指的是什么?

    DruidDataSource
    
  • 如何注入数据库连接四要素?

    setter注入
    

1.1.4 实现 C3P0 管理

完成了 DruidDataSource 的管理,接下来我们再来加深下练习,这次我们来管理C3P0​ 数据源,具体的实现步骤是什么呢?

需求:使用 Spring 的 IOC 容器来管理 C3P0 连接池对象

实现方案和上面基本一致,重点要关注管理的是哪个 bean 对象`?

步骤 1:导入C3P0​ 的依赖

pom.xml 中添加依赖

<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>

对于新的技术,不知道具体的坐标该如何查找?

  • 直接百度搜索
  • 从 mvn 的仓库https://mvnrepository.com/​​ 中进行搜索
    ​​image​​
步骤 2:配置第三方 bean

在 applicationContext.xml 配置文件中添加配置

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_db"/>
    <property name="user" value="root"/>
    <property name="password" value="root"/>
    <property name="maxPoolSize" value="1000"/>
</bean>

注意:

  • ComboPooledDataSource 的属性是通过 setter 方式进行注入
  • 想注入属性就需要在 ComboPooledDataSource 类或其上层类中有提供属性对应的 setter 方法
  • C3P0 的四个属性和 Druid 的四个属性是不一样的
步骤 3:运行程序

程序会报错,错误如下

​​image​​

报的错为ClassNotFoundException,翻译出来是类没有发现的异常​,具体的类为com.mysql.jdbc.Driver​。错误的原因是缺少 mysql 的驱动包。

分析出错误的原因,具体的解决方案就比较简单,只需要在 pom.xml 把驱动包引入即可。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

添加完 mysql 的驱动包以后,再次运行 App,就可以打印出结果:

​​image​​

注意:

  • 数据连接池在配置属性的时候,除了可以注入数据库连接四要素外还可以配置很多其他的属性,具体都有哪些属性用到的时候再去查,一般配置基础的四个,其他都有自己的默认值
  • Druid 和 C3P0 在没有导入 mysql 驱动包的前提下,一个没报错一个报错,说明 Druid 在初始化的时候没有去加载驱动,而 C3P0 刚好相反
  • Druid 程序运行虽然没有报错,但是当调用 DruidDataSource 的 getConnection()方法获取连接的时候,也会报找不到驱动类的错误

1.2 加载 properties 文件

上节中我们已经完成两个数据源druid​ 和C3P0​ 的配置,但是其中包含了一些问题,我们来分析下:

  • 这两个数据源中都使用到了一些固定的常量如数据库连接四要素,把这些值写在 Spring 的配置文件中不利于后期维护
  • 需要将这些值提取到一个外部的 properties 配置文件中
  • Spring 框架如何从配置文件中读取属性值来配置就是接下来要解决的问题。

问题提出来后,具体该如何实现?

1.2.1 第三方 bean 属性优化

1.2.1.1 实现思路

需求:将数据库连接四要素提取到 properties 配置文件,spring 来加载配置信息并使用这些信息来完成属性注入。

1.在 resources 下创建一个 jdbc.properties(文件的名称可以任意)

2.将数据库连接四要素配置到配置文件中

3.在 Spring 的配置文件中加载 properties 文件

4.使用加载到的值实现属性注入

其中第 3,4 步骤是需要大家重点关注,具体是如何实现。

1.2.1.2 实现步骤
步骤 1:准备 properties 配置文件

resources 下创建一个 jdbc.properties 文件,并添加对应的属性键值对

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=root
步骤 2:开启context​ 命名空间

在 applicationContext.xml 中开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
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
步骤 3:加载 properties 配置文件

在配置文件中使用context​ 命名空间下的标签来加载 properties 配置文件

<context:property-placeholder location="jdbc.properties"/>
步骤 4:完成属性注入

使用${key}​ 来读取 properties 配置文件中的内容并完成属性注入

<?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
            http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:property-placeholder location="jdbc.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
</beans>

至此,读取外部 properties 配置文件中的内容就已经完成。

1.2.2 读取单个属性

1.2.2.1 实现思路

对于上面的案例,效果不是很明显,我们可以换个案例来演示下:

需求:从 properties 配置文件中读取 key 为 name 的值,并将其注入到 BookDao 中并在 save 方法中进行打印。

1.在项目中添加 BookDao 和 BookDaoImpl 类

2.为 BookDaoImpl 添加一个 name 属性并提供 setter 方法

3.在 jdbc.properties 中添加数据注入到 bookDao 中打印方便查询结果

4.在 applicationContext.xml 添加配置完成配置文件加载、属性注入(${key})

1.2.2.2 实现步骤
步骤 1:在项目中添对应的类

BookDao 和 BookDaoImpl 类,并在 BookDaoImpl 类中添加name​ 属性与 setter 方法

public interface BookDao {
    public void save();
}

public class BookDaoImpl implements BookDao {
    private String name;

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

    public void save() {
        System.out.println("book dao save ..." + name);
    }
}
步骤 2:完成配置文件的读取与注入

在 applicationContext.xml 添加配置,bean的配置管理​、读取外部properties​、依赖注入​:

<?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
            http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:property-placeholder location="jdbc.properties"/>
    
    <bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl">
        <property name="name" value="${jdbc.driver}"/>
    </bean>
</beans>
步骤 3:运行程序

在 App 类中,从 IOC 容器中获取 bookDao 对象,调用方法,查看值是否已经被获取到并打印控制台

public class App {
    public static void main(String[] args) throws Exception{
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        bookDao.save();

    }
}

​​

1.2.2.3 注意事项

至此,读取 properties 配置文件中的内容就已经完成,但是在使用的时候,有些注意事项:

  • 问题一:键值对的 key 为username​ 引发的问题
    1.在 properties 中配置键值对的时候,如果 key 设置为username

    username=root666
    

    2.在 applicationContext.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
                http://www.springframework.org/schema/context/spring-context.xsd">
        
        <context:property-placeholder location="jdbc.properties"/>
        
        <bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl">
            <property name="name" value="${username}"/>
        </bean>
    </beans>
    

    3.运行后,在控制台打印的却不是root666​,而是自己电脑的用户名

    ​​image​​

    4.出现问题的原因是<context:property-placeholder/>​ 标签会加载系统的环境变量,而且环境变量的值会被优先加载,如何查看系统的环境变量?

    public static void main(String[] args) throws Exception{
        Map<String, String> env = System.getenv();
        System.out.println(env);
    }
    

    大家可以自行运行,在打印出来的结果中会有一个 USERNAME=XXX[自己电脑的用户名称]

    5.解决方案

    <?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
                http://www.springframework.org/schema/context/spring-context.xsd">
        
        <context:property-placeholder location="jdbc.properties" system-properties-mode="NEVER"/>
    </beans>
    

    system-properties-mode:设置为 NEVER,表示不加载系统属性,就可以解决上述问题。

    当然还有一个解决方案就是避免使用username​ 作为属性的key​。

  • 问题二:当有多个 properties 配置文件需要被加载,该如何配置?1.调整下配置文件的内容,在 resources 下添加jdbc.properties​,jdbc2.properties​,内容如下:
    jdbc.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
    jdbc.username=root
    jdbc.password=root
    

    jdbc2.properties

    username=root666
    

    2.修改 applicationContext.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
                http://www.springframework.org/schema/context/spring-context.xsd">
        <!--方式一 -->
        <context:property-placeholder location="jdbc.properties,jdbc2.properties" system-properties-mode="NEVER"/>
        <!--方式二-->
        <context:property-placeholder location="*.properties" system-properties-mode="NEVER"/>
        <!--方式三 -->
        <context:property-placeholder location="classpath:*.properties" system-properties-mode="NEVER"/>
        <!--方式四-->
        <context:property-placeholder location="classpath*:*.properties" system-properties-mode="NEVER"/>
    </beans>
    

    说明:

    • 方式一:可以实现,如果配置文件多的话,每个都需要配置
    • 方式二:*.properties​ 代表所有以 properties 结尾的文件都会被加载,可以解决方式一的问题,但是不标准
    • 方式三:标准的写法,classpath:​ 代表的是从根路径下开始查找,但是只能查询当前项目的根路径
    • 方式四:不仅可以加载当前项目还可以加载当前项目所依赖的所有项目的根路径下的 properties 配置文件

1.2.3 加载 properties 文件小结

** 本节主要讲解的是 properties 配置文件的加载,需要掌握的内容有:**

  • 如何开启context​​ 命名空间
    ​​image​​

  • 如何加载 properties 配置文件

    <context:property-placeholder location="" system-properties-mode="NEVER"/>
    
  • 如何在 applicationContext.xml 引入 properties 配置文件中的值

    ${key}
    

标签:xml,jdbc,配置文件,配置管理,bean,IOC,properties,加载
From: https://www.cnblogs.com/NorthPoet/p/17500212.html

相关文章

  • Spring 中的 Bean
    前言欢迎来到本篇文章,鸽了好久了,今天继续写下Spring的内容:Spring中Bean的基本概念、基本写法和3种实例化Bean的方式等。什么是Bean?我们回顾下,什么是Bean?这在上一篇文章Spring核心概念之一IoC中说过了,简而言之,一句话:被SpringIoC管理的对象,就是Bean。一个Sp......
  • 3. IOC相关内容
    1.bean相关配置‍对于bean的配置中,主要会讲解​bean基础配置​,bean的别名配置​,bean的作用范围配置​(重点),这三部分内容:1.1bean基础配置(id与class)bean标签的功能如图:​​‍这其中需要大家重点掌握的是:bean标签的id和class属性的使用。思考:class属......
  • spiring 配置类+@Bean注解的详细
    首先是自定义注解,Bean     config本身也是一个bean对象       ......
  • .net core IOC容器实现(二) -- GetService
    使用IOC容器最重要的两个步骤就是注入服务和从容器内获取服务实例。上一节聊的ServiceDescriptor其实就可以看成注入服务的步骤,这一节初步聊一聊获取服务实例的相关源码。GetServiceGetService方法是获取服务实例的入口,位于ServiceProvider这个类中publicobject?GetServ......
  • NetBeans 使用的一些小技巧提高开发效率
    一些常用的快捷键:NetBeans默认出现代码智能提示的按键是:Ctrl+Space,很不幸,大部分汉字输入法已经占用了这个热键。我们可以通过修改NetBeans的热键来用其他的:Tools->Options->Keymap,中的ShowCodeCompletionPopup的热键,这里我是用的是VisualStudio的智能提示的热键Ctr......
  • dw 的启动时初始化 动态数据源变成私有的 同时mq的监听要比bean后初始化,要么设置成懒
     将applicationContext里面获取到的bean添加到allrunner里面,进行 私有化部署数据源初始化 消费是优于一些bean,这个意思是消息消费注册的时候可能有一些bean还没有,所以等一会,消费者是先于一些bean的 Spring加载RocketMq消费者实例后会立即开始消费,不论Spring容器是否初......
  • Springboot web,三层架构, IOC&DI 使用总结2023
    Springbootweb,三层架构,IOC&DI使用总结2023一.spring.io全家桶springbootspringframework基础框架,配置繁琐,入门难度大--》springbootspringcloudspringsecurityspringdataspring发展到今天是一个生态圈,提供了若干个子项目,每个子项目用于完成特定的功能。二.sp......
  • 带你彻底掌握Bean的生命周期
    摘要:我们将深入研究SpringFramework的核心部分——SpringBean的生命周期。本文分享自华为云社区《Spring高手之路5——彻底掌握Bean的生命周期》,作者:砖业洋__。1.理解Bean的生命周期1.1生命周期的各个阶段在SpringIOC容器中,Bean的生命周期大致如下:实例化:当启动Spring应用时,I......
  • Error creating bean with name 'sqlSessionFactory' defined in class path resource
    项目启动报错原因分析背景:system模块一个月未重启过,今天重启报数据源问题原因:这里报错的原因是数据源配置问题解决:数据源配置在nacos中,拿该模块的nacos数据源配置与项目启动成功的模块的数据源配置进行对比,检查出不同,改为一样即可......
  • Spring高手之路5——彻底掌握Bean的生命周期
    1.理解Bean的生命周期1.1生命周期的各个阶段在SpringIOC容器中,Bean的生命周期大致如下:实例化:当启动Spring应用时,IOC容器就会为在配置文件中声明的每个<bean>创建一个实例。属性赋值:实例化后,Spring就通过反射机制给Bean的属性赋值。调用初始化方法:如果Bean配置了初始化方法,Spring......