spring命名空间注入和XML自动装配、引入外部配置文件

Spring

  • p命名空间注入
  • util命名空间注入
  • 基于XML的自动装配
    • 根据名称自动装配
  • Spring引入外部属性配置文件


p命名空间注入

作用:简化配置。

使用p命名空间注入的前提条件包括两个:
● 第一:在XML头部信息中添加p命名空间的配置信息:xmlns:p=“http://www.springframework.org/schema/p”
● 第二:p命名空间注入是基于setter方法的,所以需要对应的属性提供setter方法。

Customer.java

package com.w.spring6.bean;

public class Customer {
    private String name;
    private int age;

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

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

spring-p.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: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 id="customerBean" class="com.w.spring6.bean.Customer" p:name="zhangsan" p:age="20"/>

</beans>

测试程序:

@Test
public void testP(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-p.xml");
    Customer customerBean = applicationContext.getBean("customerBean", Customer.class);
    System.out.println(customerBean);
}

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

util命名空间注入

使用util命名空间可以让配置复用。
使用util命名空间的前提是:在spring配置文件头部添加配置信息。如下:

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

MyDataSource1.java

package com.w.spring6.jdbc;

import java.util.Properties;

public class MyDataSource1 {
    private Properties properties;

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "MyDataSource1{" +
                "properties=" + properties +
                '}';
    }
}

MyDataSource2.java

package com.w.spring6.jdbc;

import java.util.Properties;

public class MyDataSource2 {
    private Properties properties;

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "MyDataSource2{" +
                "properties=" + properties +
                '}';
    }
}

spring-util.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"
       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">

    <util:properties id="prop">
        <prop key="driver">com.mysql.cj.jdbc.Driver</prop>
        <prop key="url">jdbc:mysql://localhost:3306/spring</prop>
        <prop key="username">root</prop>
        <prop key="password">123456</prop>
    </util:properties>

    <bean id="dataSource1" class="com.w.spring6.jdbc.MyDataSource1">
        <property name="properties" ref="prop"/>
    </bean>

    <bean id="dataSource2" class="com.w.spring6.jdbc.MyDataSource2">
        <property name="properties" ref="prop"/>
    </bean>

</beans>

测试程序:

@Test
public void testUtil(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-util.xml");

    MyDataSource1 dataSource1 = applicationContext.getBean("dataSource1", MyDataSource1.class);
    System.out.println(dataSource1);

    MyDataSource2 dataSource2 = applicationContext.getBean("dataSource2", MyDataSource2.class);
    System.out.println(dataSource2);
}

在这里插入图片描述

基于XML的自动装配

Spring还可以完成自动化的注入,自动化注入又被称为自动装配。它可以根据名字进行自动装配,也可以根据类型进行自动装配。

根据名称自动装配

UserDao.java

package com.w.spring6.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserDao {

    private static final Logger logger= LoggerFactory.getLogger(UserDao.class);
    public void insert(){
        //System.out.println("数据库正在保存信息");
        logger.info("数据库正在保存信息");
    }

}

VipDao.java

package com.w.spring6.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VipDao {

    private static final Logger logger= LoggerFactory.getLogger(VipDao.class);
    public void insert(){
        logger.info("数据库正在保存vip信息");
    }
}

UserService.java

package com.w.spring6.service;

import com.w.spring6.dao.UserDao;
import com.w.spring6.dao.VipDao;

public class UserService {

    private UserDao userDao;
    private VipDao vipDao;

//    public void setAbc(VipDao vipDao){
//        this.vipDao=vipDao;
//    }

    public void setVipDao(VipDao vipDao){
        this.vipDao=vipDao;
    }

    //set注入的话,必须提供一个set方法
    //spring容器会调用这个set方法,来给userDao赋值
/*    //自己写的不符合javabean规范
    public void setMySQLUserDao(UserDao xyz){
        this.userDao=xyz;
    }*/

    //idea自动生成的符合javabean规范
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void saveUser(){
        userDao.insert();
        vipDao.insert();

    }
}

spring-autowire.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">

    <bean id="userService" class="com.w.spring6.service.UserService" autowire="byName"/>

    <bean id="userDao" class="com.w.spring6.dao.UserDao"/>

    <bean id="vipDao" class="com.w.spring6.dao.VipDao"/>

</beans>

测试程序:

    @Test
    public void testAutowireByName(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-autowire.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.saveUser();
    }

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

Spring引入外部属性配置文件

在类路径下新建jdbc.properties文件,并配置信息

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/spring
username=root
password=123456

在spring配置文件中引入context命名空间,配置使用jdbc.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">
<!--
引入外部的properties文件
第一步:引入context命名空间
第二步:使用标签location属性来指定属性配置文件的路径

-->

    <context:property-placeholder location="jdbc.properties"/>

        <bean id="dataSource" class="com.w.spring6.jdbc.MyDataSource">
            <property name="driver" value="${jdbc.driverClass}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>

</beans>

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

error C2143的原因及解决办法

error C2143的原因及解决办法 在C编程中&#xff0c;经常会遇到各种错误。其中之一就是error C2143。本文将讨论error C2143的原因&#xff0c;并给出相应的解决办法。 error C2143通常是由于语法错误引起的。具体而言&#xff0c;C2143错误表示编译器无法识别代码中的某个符…

鲲鹏920的架构分析

*本文信息主要来源于书籍《鲲鹏处理器架构与编程》以及论文《Kunpeng 920: The First 7-nm Chiplet-Based 64-Core ARM SoC for Cloud Services》 * 笔者已然写了一篇上述论文的分析博客&#xff0c;但尚觉论文内容对chiplet架构描述不够清晰&#xff0c;因此查阅《鲲鹏处理器…

ECharts修改tooltip样式

tooltip不支持rich&#xff0c;formatter返回的是html片段&#xff0c;可以在这个返回的片段里面增加类名。以达到更改tooltip文字格式的效果。所以&#xff0c;直接写html的样式就可以 静态数据 formatter: (params) > {console.log(params, params)return <h2 style&q…

C++多态特性

&#x1f388;个人主页:&#x1f388; :✨✨✨初阶牛✨✨✨ &#x1f43b;强烈推荐优质专栏: &#x1f354;&#x1f35f;&#x1f32f;C的世界(持续更新中) &#x1f43b;推荐专栏1: &#x1f354;&#x1f35f;&#x1f32f;C语言初阶 &#x1f43b;推荐专栏2: &#x1f354;…

Redis之主从复制

文章目录 一、什么是Redis主从复制&#xff1f;1.作用2.配置主从复制的原因3.环境配置 二、一主二从三、复制原理四、链路总结 一、什么是Redis主从复制&#xff1f; 主从复制&#xff0c;是指将一台Redis服务器的数据&#xff0c;复制到其他的Redis服务器。前者称为主节点(ma…

HTML点击链接强制触发下载

常见网页中会有很多点击链接即下载的内容&#xff0c;以下示范一下如何实现 <a href"文件地址" download"下载的文件名字&#xff08;不包括后缀&#xff09;">强制下载</a> 下面举个例子&#xff1a; <a href"./image/test.jpg"…

Azure 机器学习 - 如何使用模板创建安全工作区

目录 先决条件了解模板配置模板连接到工作区疑难解答错误&#xff1a;Windows 计算机名的长度不能超过 15 个字符&#xff0c;并且不能全为数字或包含以下字符 本教程介绍如何使用 [Microsoft Bicep]和 [Hashicorp Terraform]模板创建以下 Azure 资源&#xff1a; Azure 虚拟网…

王学岗visibility改变后调用onLayout()

自定义控件的时候发现了一个bug。 Button位移动画执行结束后我设置了一个不相关的TextView的可见性由gone变为visible.令人郁闷的是&#xff0c;只要我注释的地方放开。动画执行结束后button都会重新绘制在位移动画开始的位置。注释掉这段代码就正常。 经过分析后得知 View的Vi…

算法:FloodFill算法

文章目录 算法原理图像渲染岛屿数量岛屿的最大面积被围绕的区域太平洋大西洋水流问题扫雷游戏衣橱整理 算法原理 FLoodFill算法通俗来讲&#xff0c;就是洪水给地势带来的变化&#xff0c;而实际上题目要求的就是一个连通块问题&#xff0c;那本质还是暴搜和DFS/BFS相结合&…

dream_ready

&#x1f9f8;欢迎来到dream_ready的博客&#xff0c;&#x1f4dc;相信您对这篇博客也感兴趣o (ˉ▽ˉ&#xff1b;) Python 语法及入门 &#xff08;超全超详细&#xff09; 专为Python零基础 一篇博客让你完全掌握Python语法 路的尽头是什么&#xff1f;这是我年少时常伴在嘴…

【题解】2023-11-11 B层模拟赛T1

宣传一下 算法提高课整理 CSDN个人主页&#xff1a;更好的阅读体验 原题链接 CF461B 题目描述 一棵树有 n n n 个节点&#xff0c; n − 1 n − 1 n−1 条边。树上的节点有两种&#xff1a;黑&#xff0c;白节点。 Tyk 想断掉一些边把树分成很多部分。 他想要保证每个部…

【chat】4: ubuntu20.04:数据库创建:mysql8 导入5.7表

【chat】3: ubutnu 安装mysql-8 并支持远程访问 已经支持 8.0的SQLyog 远程访问:大神2021年的文章:sql是5.7的版本,我使用的ubuntu20.04,8.0版本:chat数据库设计 C++搭建集群聊天室(七):MySQL数据库配置 及项目工程目录配置 User表,以id 唯一标识 Friend 表,自己的id…

如何在 Windows 11 上恢复丢失的文件?(4种方法)

在 Windows 11 设备上丢失重要文件感觉就像一场噩梦。这是您希望时光倒流并撤消意外删除或避免那些意外的系统故障的时刻之一。这种情况带来的挫败感和焦虑感简直难以承受。但是&#xff0c;嘿&#xff0c;不要绝望&#xff01;我们随时为您提供帮助。 在这本真诚的指南中&…

JavaFX增删改查其他控件01界面展示

界面展示 小技巧 增删改查思路--查 底层select * from 表 where sname like %% --1.拿文本框的关键字 --2.调模糊查询的方法 myShow("")--删 底层 delete from tb_stu where sid? --1.想方设法拿学号 --1.先拿到用户所选中的学生对象 Student --2.调用方法传对象.g…

Run highlighted commands using IDE

背景 有时候在 IEDE 的命令行中输入命令&#xff0c;会弹出如下提示&#xff0c;或者命令被着了背景色了&#xff0c;是怎么回事&#xff1f; 其实就是提示你可以使用 IDEA 的功能替代命令行。比如使用ctrlenter或cmdenter之后使用的就是 IDEA 里的功能 直接enter运行&#x…

国家数据局正式揭牌,2030年数据要素市场规模或破万亿

10月25日&#xff0c;国家数据局正式挂牌&#xff01; 自今年3月国务院通过《党和国家机构改革方案》提出组建国家数据局以来&#xff0c;国家数据局的组建工作一直在紧锣密鼓地进行中。经过7个月的筹备工作&#xff0c;国家数据局于2023年10月25日挂牌成立。 根据《党和国家机…

JWT令牌

引入maven依赖坐标 <!--java-jwt坐标--> <dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.13.0</version></dependency> <!--单元测试坐标--><dependency>&…

ROS 学习应用篇(三)话题Topic学习之自定义话题消息的类型的定义与调用

自定义消息类型的定义 Person.msg文件的定义&#xff08;数据接口文件的定义&#xff09; 创建msg文件 首先在功能包下新建msg文件夹&#xff0c;接着在该文件夹下创建文件。 定义msg文件内容 一个消息最重要的就是数据结构类型。这就需要引入一个msg文件&#xff0c;用于…

css:两个行内块元素和图片垂直居中对齐

目录 两个行内块元素垂直居中对齐图片垂直居中问题图片和文字垂直居中对齐参考文章 两个行内块元素垂直居中对齐 先看一段代码&#xff1a; <style> .box {width: 200px;height: 200px;line-height: 200px;font-size: 20px;text-align: center;display: inline-block;b…

Python制作国旗头像

今天教大家用几行代码快速实现一个国庆风头像&#xff0c;效果是这样的 素材&#xff1a;一张头像、一张国旗图片 思路&#xff1a;将国旗图片的每个像素点的透明度从左至右&#xff0c;从上到下逐次递减后&#xff0c;将其盖在头像上面就形成了最终的效果图。 完整代码&…