08 SpringBoot 自定定义配置

SpringBoot自定义配置有三种方式:

使用@PropertySource进行自定义配置
使用@ImportResource进行自定义配置
使用@Configuration进行自定义配置

@PropertySource

​ 如果将所有的配置都集中到 application.properties 或 application.yml 中,那么这个配置文件会十分的臃肿且难以维护,因此我们通常会将与 Spring Boot 无关的配置(例如自定义配置)提取出来,写在一个单独的配置文件中,并在对应的 JavaBean 上使用 @PropertySource 注解指向该配置文件。

步骤一:

以 DemoApplication为例,将与 user’ 相关的自定义配置移动到 src/main/resources 下的 user.properties 中

注意,必须把 application.properties 或 application.yml 中的相关配置删除

如下图
image-20221012142956929

person.properties 的配置如下

user.id=30
user.name="Administrator"
user.sex="man"
user.age=32
user.salary=33000.45
user.address="cehngdushi"
user.jobName="教师"
user.hibernate=2022/09/26#对数组books赋值
user.books[0].name=bigdata
user.books[0].price=32.62d
user.books[1].name=python
user.books[1].price=102.62d#对数组names赋值
user.names[0]="jianghuan"
user.names[1]="xiangjie"
user.names[2]="taoshi"#students中的key-value表示学生姓名和学号
user.students.key1=2020120014
user.students.key2=2020120015
user.students.key3=2020120016
user.students.key4=2020120017

步骤二:

在 User 使用 @PropertySource 注解指向 user.properties,代码如下。

创建Book实体
public class Book {private String name;private Double price;.... 此处省略有参无参构造函数 及 setter、getter方法和toString方法
}创建User实体类
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
*
* @ConfigurationProperties:告诉 SpringBoot 将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能;
*/@Component
@PropertySource("classpath:user.properties") //指向对应的配置文件
@ConfigurationProperties(prefix = "user") // 使用user.properties中的进行注入
public class User {private String id;private String name;private String sex;private Integer age;private Double salary;private String address;private Date hibernate;private Book[] books;private List<String> names;private Map<String,Integer> students; //students中的key-value表示学生姓名和学号.... 此处省略有参无参构造函数 及 setter、getter方法和toString方法}

注意:

  • @PropertySource()可以同时支持多个配置文件用逗号隔开,例如@PropertySource(locations={“classpath:user.properties”,“classpath:emp.properties”})

步骤三:

重启主启动类,在 DemoApplication 项目的 主启动类 中获取IOC容器,从IOC容器中获取Userbean,通过打印userbean展示配置文件中各个属性值。

@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {//1、返回IOC容器ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);//2、查看容器中的组件User user = run.getBean(User.class);System.out.println(user);}
}

步骤四:

查看运行结果

image-20221012143057098

默认情况下,Spring Boot 中是不包含任何的 Spring 配置文件的,即使我们手动添加 Spring 配置文件到项目中,也不会被识别。那么 Spring Boot 项目中真的就无法导入 Spring 配置吗?答案是否定的。

Spring Boot 为了我们提供了以下 2 种方式来导入 Spring 配置:

  • 使用 @ImportResource 注解加载 Spring 配置文件
  • 使用全注解方式加载 Spring 配置

@ImportResource

如有是使用springboot项目来重构以前用SSM开发的项目,并且不想重写原有的实体类或者其他类及其spring的配置文件,此时可以使用注解**@ImportResource**导入spring的配置文件,让配置文件生效。

步骤一:

在 DemoApplication 项目的 com.example.demo.bean 中创建一个名为 User 的实体类,代码如下:

创建Book实体
public class Book {private String name;private Double price;.... 此处省略有参无参构造函数 及 setter、getter方法和toString方法
}创建User实体类
public class User {private String id;private String name;private String sex;private Integer age;private Double salary;private String address;private Date hibernate;private Book[] books;private List<String> names;private String jobName;private Map<String,Integer> students; //students中的key-value表示学生姓名和学号.... 此处省略有参无参构造函数 及 setter、getter方法和toString方法}

步骤二:

在该项目的 resources 下添加一个名为 beans.xml 的 Spring 配置文件,使用标签创建Book和User实体类对象和值的注入,配置代码如下。

<?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"><!--     使用bean标签创建日期对象--><bean id="date" class="java.util.Date"></bean><!--     使用bean标签创建三个book对象,并注入值--><bean id="book1" class="com.example.demo.bean.Book"><property name="name" value="bigdata"></property><property name="price" value="32.62"></property></bean><bean id="book2" class="com.example.demo.bean.Book"><property name="name" value="java"></property><property name="price" value="72.62"></property></bean><bean id="book3" class="com.example.demo.bean.Book"><property name="name" value="python"></property><property name="price" value="102.62"></property></bean><!--     使用bean标签创建user对象,并注入值--><bean id="user" class="com.example.demo.bean.User" ><property name="id" value="30"></property><property name="name" value="Administrator"></property><property name="sex" value="chuntian"></property><property name="age" value="32"></property><property name="salary" value="33000.45"></property><property name="address" value="cehngdushi"></property><property name="jobName" value="教师"></property><property name="hibernate" ref="date"></property><property name="books" ><array><ref bean="book1"/><ref bean="book2"/><ref bean="book3"/></array></property><property name="names"><list><value>"jianghuan"</value><value>"xiangjie"</value><value>"taoshi"</value></list></property><property name="students"><map><entry key="key1" value="2020120014"/><entry key="key2" value="2020120015"/><entry key="key3" value="2020120016"/><entry key="key4" value="2020120017"/></map></property></bean></beans>

步骤三:

在主启动程序类上使用 @ImportResource 注解,将 Spring 配置文件 beans.xml 加载到项目中,代码如下

@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class DemoApplication {public static void main(String[] args) {//1、返回IOC容器ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);boolean bl = run.containsBean("user"); //在bean.xml中配置的bean的id值为user的if (bl) {System.out.println("user 已经添加到 IOC 容器中");} else {System.out.println("user 没添加到 IOC 容器中");}//2、查看容器中的组件User user = run.getBean(User.class);System.out.println(user);}
}

步骤四:

启动主启动类,运行结果如下:image-20221012143911843

@Configuration

全注解方式加载 Spring 配置
如有是使用springboot项目来重构以前用SSM开发的项目,并且不想重写原有的实体类或者其他类及其spring的配置文件,此时可以使用注解@ImportResource导入spring的配置文件,让配置文件生效。

@Configuration底层代码

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {@AliasFor(annotation = Component.class)String value() default "";boolean proxyBeanMethods() default true;
}

@Configuration是配置类注解,是spring的底层注解;从@Component可以看出配置类也是一个组件;这个注解@Configuration用在类上,表示告诉spring这个类是配置类===spring配置文件。

Spring Boot 推荐我们使用@Configuration全注解的方式加载 Spring 配置,其实现方式如下:

  1. 使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;
  2. 配置类内部可以包含有一个或多个被 @Bean 注解的方法,这些方法会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描,构建 bean 定义(相当于 Spring 配置文件中的标签),方法的返回值会以组件的形式添加到容器中,组件的 id 就是方法名。

步骤一:

在 DemoApplication 项目的 com.example.demo.service中创建一个名为 MyService的服务类,代码如下:

//创建MyService 
public class MyService {
}

步骤二:

在 com.example.demo.config 包下添加一个名为 DemoConfig 的配置类,并在类上使用注解@Configuration,代码如下。

@Configuration // 告诉spring这是一个配置类 ==  spring配置文件
public class DemoConfig {@Bean // 给容器中添加组件,以方法名为组件id,返回的值就是组件public MyService  myService(){return new MyService();}
}

上述代码等价与在xml中配置bean标签

<bean id="user" class="com.example.demo.servvice.MyService"></bean>

关于@configuration注解的解释:

1.@Configuration 注解用于定义一个配置类,相当于 Spring 的配置文件

2.配置类中包含一个或多个被 @Bean 注解的方法,该方法相当于 Spring 配置文件中的 标签定义的组件

3.@Bean等价spring配置文件中 标签

4.myService()方法的返回值以组件的形式添加到容器中

5.方法名myService()是组件 id(相当于 标签的属性 id)

步骤三:

在主启动程序类上代码如下。

@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {//1、返回IOC容器ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);boolean bl = run.containsBean("myService"); //配置类中@Bean标注的方法名if (bl) {System.out.println("myService 已经添加到 IOC 容器中");} else {System.out.println("myService 没添加到 IOC 容器中");}//2、查看容器中的组件MyService myService= run.getBean(MyService .class);System.out.println(myService);}
}

步骤四:

启动主启动类,运行结果如下:

image-20221012144758184

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

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

相关文章

Python闯LeetCode--第1题:两数之和

Problem: 1. 两数之和 文章目录 思路解题方法复杂度Code 思路 看到这道题第一思路就是暴力破解&#xff0c;枚举&#xff0c;两个for循环遍历&#xff0c;直到找到满足要求的答案。主要因题目假设只有一组满足结果的答案&#xff0c;因此难度大大降低&#xff0c;作为第一道题&…

解决javadoc一直找不到路径的问题

解决javadoc一直找不到路径的问题 出现以上问题就是我们在下载jdk的时候一些运行程序安装在C:\Program Files\Common Files\Oracle\Java\javapath下&#xff1a; 一开始是没有javadoc.exe文件的&#xff0c;我们只需要从jdk的bin目录下找到复制到这个里面&#xff0c;就可以使用…

去掉eslint

1、在vue.config.js文件里加上下面的代码&#xff0c;然后重启就可以了&#xff01; 2、vue.config.js文件代码&#xff1a; const { defineConfig } require(vue/cli-service) module.exports defineConfig({transpileDependencies: true,lintOnSave: false })

堆栈溢出的攻击 -fno-stack-protector stack smash 检测

在程序返回的一条语句堆栈项目处&#xff0c;用新函数的起始地址覆盖&#xff0c;将会跳转到执行新函数。 现在系统对这个行为做了判断&#xff0c;已经无法实施这类攻击或技巧。 1&#xff0c;测试代码 #include <stdio.h> void cc() {printf("I am cc( )\n"…

设置SSHkeys多服务器免登录配置(ssh config)

一、背景&#xff1a; 多邮箱或者多git账号进行同一台电脑开发的情况。 有时候&#xff0c;开发时可能会面临一个情况&#xff0c;就是通过自己的电脑&#xff0c;可能同时需要开发多个不同地方的项目&#xff0c;或者说&#xff0c;自己建立的项目已经配置好SSH验证免密登录&a…

C# WPF入门学习主线篇(二十三)—— 控件模板(ControlTemplate)和数据模板(DataTemplate)

C# WPF入门学习主线篇&#xff08;二十三&#xff09;—— 控件模板&#xff08;ControlTemplate&#xff09;和数据模板&#xff08;DataTemplate&#xff09; 在WPF开发中&#xff0c;控件模板&#xff08;ControlTemplate&#xff09;和数据模板&#xff08;DataTemplate&am…

基于Python+OpenCV+SVM车牌识别系统(GUI界面)【W3】

简介&#xff1a; 随着交通管理的日益复杂化和智能化需求的增加&#xff0c;车牌识别系统在安防、智慧交通管理等领域中扮演着重要角色。传统的车牌识别系统主要基于图像处理和模式识别技术&#xff0c;随着计算机视觉技术的发展&#xff0c;基于Python、OpenCV和机器学习算法的…

Vue3新特性指南:探索新增指令、内置组件和改进

Vue.js是一款流行的JavaScript框架,用于构建现代Web应用。Vue3是Vue.js的最新版本,引入了许多新特性和改进。本文将介绍Vue3新增的指令、内置组件以及其他值得关注的改进,并提供使用组合式API的用法示例。 一、新增指令 v-is指令: v-is指令用于动态组件,可以根据表达式的值来…

2024年6月-Docker配置镜像代理

步骤1&#xff1a;编辑 daemon.json 文件 vim /etc/docker/daemon.json步骤2&#xff1a;添加配置 将以下内容粘贴到文件中&#xff1a; {"insecure-registries": ["192.168.0.99:8800"],"data-root": "/mnt/docker","registr…

redis 故障处理: 持续更新

redis 内存快满&#xff1a; 突发性&#xff1a; 1.1 当突发的时候&#xff0c;先进行扩容redis 内存&#xff1a; CONFIG SET maxmemory 6G 1.2 通过monter 获取当前redis 请求&#xff0c;发送给开发&#xff0c;让开发进行处理一下缓慢性&#xff1a; 进行扫描一下redis…

文件初阶入门(葵花宝典)

1. 文件的顺序读写 1.1 顺序读写函数的介绍 函数名 功能 适用于 fgetc 字符输入函数 所有输入流 fputc 字符输出函数 所有输出流 fgets 文本行输入函数 所有输入流 fputs 文本行输出函数 所有输出流 f…

小数二分个人见解

小数二分 小数二分题目 小数二分 整数二分 是找边界点&#xff0c;而小数二分找的是 近似值。 整数二分是在一个整型数组当中 查找&#xff0c;而小数二分是在数轴中 查找&#xff0c;都是每次可以排除一半的区间&#xff0c;只不过小数二分中while循环内的结束条件和整数二分…

大模型中的计算精度——FP32, FP16, bfp16之类的都是什么???

大模型中的计算精度——FP32, FP16, bfp16之类的都是什么&#xff1f;&#xff1f;&#xff1f; 这些精度是用来干嘛的&#xff1f;&#xff1f;混合精度 mixed precision training什么是混合精度&#xff1f;怎么转换呢&#xff1f; 为什么大语言模型通常使用FP32精度训练量化…

深入探索Spring Boot的条件装配与条件注解

Spring Boot 的条件装配&#xff08;Conditional装配&#xff09;是一个强大的功能&#xff0c;它允许你根据特定的条件来决定哪些配置类、beans 或组件应该被加载到Spring应用上下文中。这有助于创建更灵活、更模块化的Spring Boot应用程序。 在Spring Boot中&#xff0c;条件…

ECharts 数据的视觉映射

ECharts 数据的视觉映射 ECharts 是一个由百度开源的&#xff0c;基于 JavaScript 的数据可视化库。它提供了丰富的图表类型和灵活的配置选项&#xff0c;使得用户能够轻松地将数据转换为直观的图表。在 ECharts 中&#xff0c;数据的视觉映射是一个核心功能&#xff0c;它允许…

关于element-plus中el-select自定义标签及样式的问题

关于element-plus中el-select自定义标签及样式的问题 我这天天的都遇到各种坑&#xff0c;关于自定义&#xff0c;我直接复制粘贴代码都实现不了&#xff0c;研究了一下午&#xff0c;骂骂咧咧了一下午&#xff0c;服气了。官网代码实现不了&#xff0c;就只能 “ 曲线救国 ”…

前端面经总结、学习【2023秋招】

目录 1、浏览器输入URL发生了什么&#xff1f;2、跨域是什么&#xff1f;如何解决跨域问题&#xff1f;3、cookie 是什么&#xff1f;4、cookie 能做什么&#xff1f; 1、浏览器输入URL发生了什么&#xff1f; URL解析&#xff1a;判断浏览器输入的是搜索内容还是URL&#xff…

昂科烧录器支持Prolific旺玖科技的电力监控芯片PL7413C1FIG

芯片烧录行业领导者-昂科技术近日发布最新的烧录软件更新及新增支持的芯片型号列表&#xff0c;其中Prolific旺玖科技的高度集成的电力监控芯片PL7413C1FIG已经被昂科的通用烧录平台AP8000所支持。 PL7413C1FIG是一款高度集成的电力监控芯片&#xff0c;用于测量电力使用情况的…

Mysql-题目02

下面列出的&#xff08; DBMS &#xff09;是数据库管理系统的简称。 A、DB&#xff08;数据库&#xff09; B、DBA C、DBMS(数据库管理系统&#xff09; D、DBS&#xff08;数据库系统) 以下选项中&#xff0c;&#xff08; 概念模式 &#xff09;面向数据库设计人员&…

MySQL-分组函数

041-分组函数 重点&#xff1a;所有的分组函数都是自动忽略NULL的 分组函数的执行原则&#xff1a;先分组&#xff0c;然后对每一组数据执行分组函数。如果没有分组语句group by的话&#xff0c;整张表的数据自成一组。 分组函数包括五个&#xff1a; max&#xff1a;最大值mi…