写点什么

一文讲清楚 SpringBoot 六种读取配置方式

作者:王小凡
  • 2022 年 7 月 26 日
  • 本文字数:5992 字

    阅读完需:约 20 分钟

一文讲清楚SpringBoot六种读取配置方式

1 SpringBoot 工程创建

1.1 maven 工程创建

使用开发工具创建一个纯净 maven 工程

1.2 引入依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"	 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">       <modelVersion>4.0.0</modelVersion>    <groupId>com.java.front.spring.boot</groupId>    <artifactId>spring-boot-java-front</artifactId>    <version>1.0.0-SNAPSHOT</version>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.1.5.RELEASE</version>    </parent>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>    </dependencies></project>
复制代码

1.3 新增订单模型

package com.java.front.spring.boot.model;import java.util.Date;import java.util.List;import java.util.Map;import com.fasterxml.jackson.annotation.JsonFormat;
public class OrderInfoModel {
private String orderId;
private Integer orderPrice;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime;
private List<String> extendList;
private Map<String, String> extendMap;
// getter setter}
复制代码

1.4 新增访问端点

package com.java.front.spring.boot.controller;import java.util.Date;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.java.front.spring.boot.model.OrderInfoModel;
@Controllerpublic class OrderController {
@ResponseBody @RequestMapping("getOrder") public OrderInfoModel queryOrder() { OrderInfoModel orderInfo = new OrderInfoModel(); orderInfo.setOrderId("orderId_111"); orderInfo.setOrderPrice(100); orderInfo.setCreateTime(new Date()); return orderInfo; }}
复制代码

1.5 创建启动类

package com.java.front.spring.boot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class JavaFrontApplication {
public static void main(String[] args) { SpringApplication.run(JavaFrontApplication.class, args); }}
复制代码

1.6 运行启动类

Run AS > Spring Boot App
复制代码


1.7 访问测试

http://localhost:8080/getOrder
{"orderId":"orderId_111","orderPrice":100,"createTime":"2022-04-23 08:10:51","extendList":null,"extendMap":null}
复制代码


2 方式一:XML

2.1 新增订单服务

package com.java.front.spring.boot.service;import com.java.front.spring.boot.model.OrderInfoModel;
public interface OrderService { public OrderInfoModel createOrder();}

package com.java.front.spring.boot.service;import java.util.Date;import com.java.front.spring.boot.model.OrderInfoModel;
public class OrderServiceImpl implements OrderService {
@Override public OrderInfoModel createOrder() { String orderId = "orderId_222"; OrderInfoModel orderInfo = new OrderInfoModel(); orderInfo.setOrderId(orderId); orderInfo.setOrderPrice(200); orderInfo.setCreateTime(new Date()); return orderInfo; }}
复制代码


2.2 新增配置文件

src/main/resources/spring-biz.xml

# src/main/resources/spring-biz.xml
<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="orderService" class="com.java.front.spring.boot.service.OrderServiceImpl" />
</beans>
复制代码

2.3 启动类引入资源文件

package com.java.front.spring.boot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.ImportResource;
@ImportResource(locations = { "classpath:spring-biz.xml" })@SpringBootApplicationpublic class JavaFrontApplication {
public static void main(String[] args) { SpringApplication.run(JavaFrontApplication.class, args); }}
复制代码


2.4 新增访问端点

package com.java.front.spring.boot.controller;import java.util.Date;import javax.annotation.Resource;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.java.front.spring.boot.model.OrderInfoModel;import com.java.front.spring.boot.service.OrderService;
@Controllerpublic class OrderController {
@Resource private OrderService orderService;
@ResponseBody @RequestMapping("createOrder") public OrderInfoModel createOrder() { OrderInfoModel orderInfo = orderService.createOrder(); return orderInfo; }}
复制代码


2.5 启动并访问

http://localhost:8080/createOrder
{"orderId":"orderId_222","orderPrice":200,"createTime":"2022-04-23 08:36:03","extendList":null,"extendMap":null}
复制代码


3 方式二:@Bean

3.1 新增配置类

删除配置 spring-biz.xml 并且新增如下配置:

package com.java.front.spring.boot.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.java.front.spring.boot.service.OrderService;import com.java.front.spring.boot.service.OrderServiceImpl;
@Configurationpublic class OrderServiceConfig {
@Bean public OrderService orderService() { return new OrderServiceImpl(); }}
复制代码

3.2 启动并访问

http://localhost:8080/createOrder
{"orderId":"orderId_222","orderPrice":200,"createTime":"2022-04-23 09:15:03","extendList":null,"extendMap":null}
复制代码


4 方式三:@Bean 增强

4.1 新增订单服务

package com.java.front.spring.boot.service;import java.util.Date;import com.java.front.spring.boot.model.OrderInfoModel;
public class OrderServiceAImpl implements OrderService {
@Override public OrderInfoModel createOrder() { String orderId = "orderId_AAA"; OrderInfoModel orderInfo = new OrderInfoModel(); orderInfo.setOrderId(orderId); orderInfo.setOrderPrice(200); orderInfo.setCreateTime(new Date()); return orderInfo; }}

package com.java.front.spring.boot.service;import java.util.Date;import org.springframework.stereotype.Service;import com.java.front.spring.boot.model.OrderInfoModel;
@Servicepublic class OrderServiceBImpl implements OrderService {
@Override public OrderInfoModel createOrder() { String orderId = "orderId_BBB"; OrderInfoModel orderInfo = new OrderInfoModel(); orderInfo.setOrderId(orderId); orderInfo.setOrderPrice(200); orderInfo.setCreateTime(new Date()); return orderInfo; }}
复制代码

4.2 修改配置类

package com.java.front.spring.boot.config;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.java.front.spring.boot.service.OrderService;import com.java.front.spring.boot.service.OrderServiceAImpl;
@Configurationpublic class OrderServiceConfig {
/** * 默认情况使用此实例 * * 如果容器有其它实例则使用其它实例 */ @Bean @ConditionalOnMissingBean(OrderService.class) public OrderService orderService() { return new OrderServiceAImpl(); }}
复制代码

4.3 启动并访问

http://localhost:8080/createOrder
{"orderId":"orderId_BBB","orderPrice":200,"createTime":"2022-04-23 09:40:13","extendList":null,"extendMap":null}
复制代码

5 方式四:application.properties

5.1 引入依赖

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-configuration-processor</artifactId>    <optional>true</optional></dependency>
复制代码

5.2 新增配置文件

# src/main/resources/application.properties
server.port=9999spring.jackson.date-format=yyyy-MM-dd HH:mm:ssspring.jackson.time-zone=GMT+8
order.orderId=orderId_abcorder.orderPrice=500order.createTime=2022/01/01 11:00:00order.extendList=a,b,corder.extendMap.k1=v1order.extendMap.k2=v2
java.front.test.boolean=truejava.front.test.list=a,b,cjava.front.test.map={"k1":"v1","k2":"v2"}
复制代码

5.3 新增订单模型

package com.java.front.spring.boot.model;import java.util.Date;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;
@Component@ConfigurationProperties(prefix = "order")public class OrderInfoModelV2 {
// ---------application.properties start with order config---------
private String orderId;
private Integer orderPrice;
private Date createTime;
private List<String> extendList;
private Map<String, String> extendMap;
// ---------application.properties use @value to read-------------
@Value("${java.front.test.boolean:false}") private Boolean testBoolean;
@Value("#{'${java.front.test.list:{}}'.split(',')}") private List<String> testList;
@Value("#{${java.front.test.map:null}}") private Map<String, String> testMap;
@Value("#{3*10}") private Integer testInteger;
// -------------------------getter setter-------------------------}// -------------------------getter setter-------------------------
复制代码

5.4 新增访问端点

package com.java.front.spring.boot.controller;import java.util.Date;import javax.annotation.Resource;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.java.front.spring.boot.model.OrderInfoModel;import com.java.front.spring.boot.model.OrderInfoModelV2;import com.java.front.spring.boot.service.OrderService;
@Controllerpublic class OrderController {
@Resource private OrderInfoModelV2 orderInfoModelV2;
@ResponseBody @RequestMapping("queryOrderFromConfig") public OrderInfoModelV2 queryOrderFromConfig() { return orderInfoModelV2; }}
复制代码

5.5 启动并访问

http://localhost:9999/queryOrderFromConfig
{"orderId":"orderId_abc","orderPrice":500,"createTime":"2022-01-01 11:00:00","extendList":["a","b","c"],"extendMap":{"k1":"v1","k2":"v2"},"testBoolean":true,"testList":["a","b","c"],"testMap":{"k1":"v1","k2":"v2"},"testInteger":30}
复制代码


6 方式五:@PropertySource

6.1 拆分订单配置

# src/main/resources/order.properties
order.orderId=orderId_abcorder.orderPrice=500order.createTime=2022/01/01 11:00:00order.extendList=a,b,corder.extendMap.k1=v1order.extendMap.k2=v2
java.front.test.boolean=truejava.front.test.list=a,b,cjava.front.test.map={"k1":"v1","k2":"v2"}
复制代码

6.2 @PropertySource

@PropertySource(value = { "order.properties" })@Component@ConfigurationProperties(prefix = "order")public class OrderInfoModelV2 {}
复制代码


6.3 启动并访问

http://localhost:9999/queryOrderFromConfig
{"orderId":"orderId_abc","orderPrice":500,"createTime":"2022-01-01 11:00:00","extendList":["a","b","c"],"extendMap":{"k1":"v1","k2":"v2"},"testBoolean":true,"testList":["a","b","c"],"testMap":{"k1":"v1","k2":"v2"},"testInteger":30}
复制代码


7 方式六:application.yaml

7.1 新增配置文件

# src/main/resources/application.yaml
server: port: 9999 spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8
order: orderId: orderId_abc orderPrice: 500 createTime: 2022/01/01 11:00:00 extendList: - a - b - c extendMap: k1: v1 k2: v2
java: front: test: boolean: true list: 'a,b,c' map: '{"k1":"v1","k2":"v2"}'
复制代码

7.2 启动并访问

http://localhost:9999/queryOrderFromConfig
{"orderId":"orderId_abc","orderPrice":500,"createTime":"2022-01-01 11:00:00","extendList":["a","b","c"],"extendMap":{"k1":"v1","k2":"v2"},"testBoolean":true,"testList":["a","b","c"],"testMap":{"k1":"v1","k2":"v2"},"testInteger":30}
复制代码

8 文章总结

本文梳理了 SpringBoot 六种读取配置方式,大家在项目中可以进行灵活组合和应用,希望本文对大家有所帮助。

用户头像

王小凡

关注

还未添加个人签名 2022.07.26 加入

还未添加个人简介

评论

发布
暂无评论
一文讲清楚SpringBoot六种读取配置方式_Java_王小凡_InfoQ写作社区