SpringBoot注解配置文件自动映射到属性和实体类(解决硬编码问题)

本文介绍SpringBoot中如何使用注解将配置文件中的属性自动映射到Java属性和实体类,解决硬编码问题,提高代码灵活性。通过具体示例展示在Controller类中注入属性及配置实体类的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot注解配置文件自动映射到属性和实体类(解决硬编码问题)

配置文件自动映射解决的问题

可以从配置文件自定义属性值,通过注解自动映射到属性或者实体类中,解决代码中的硬编码问题

配置文件自动映射到属性

以一个上传文件控制类中需要注入上传图片路径属性为例:

1.在Controller类上加配置文件路径注解:

这里直接在application.properties中直接自定义的需要注入的配置属性信息,所以就引入application.properties

@PropertySource({"classpath:application.properties"})

在这里插入图片描述
2.在application.properties配置文件中自定义需要注入的属性:
在这里插入图片描述
3.在Controller中编写被注入属性:

   @Value("${web.file.path}")
   private String filePath;

在这里插入图片描述

配置文件自动映射到实体类

配置文件自动映射到属性只能在Controller类中注入
为了解决这种局限性
可以配置文件自动映射到实体类
然后再依赖注入实体类
1.定义一个用作映射的实体类ServerSetting.java:

package com.springboot20.xdclass.springboot.demo2.setting;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource({"classpath:resources.properties"})
@ConfigurationProperties
public class ServerSetting {

   @Value("${test.domain}")
   private String domain;
   
   @Value("${test.name}")
   private String name;

   public String getDomain() {
   	return domain;
   }

   public void setDomain(String domain) {
   	this.domain = domain;
   }

   public String getName() {
   	return name;
   }

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

}

注意:以下三个类注解
在这里插入图片描述

2.定义一个配置信息文件resources.properties:

在这里插入图片描述

3.ServerSetting.java中用@Value给属性配文件中的值:
在这里插入图片描述
4.编写单元测试类TestSetting.java:

package com.springboot20.xdclass.springboot.demo2;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.springboot20.xdclass.springboot.demo2.setting.ServerSetting;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestSetting {

   @Autowired
   private ServerSetting serverSetting;//注入ServerSetting
   
   @Test
   public void testSetting(){
   	System.out.println(serverSetting.getDomain());
   	System.out.println(serverSetting.getName());
   }
   
}

5.单元测试结果:
控制台输出结果:
在这里插入图片描述
证明配置信息自动注入实体类

注意以下这种情况ServerSetting.java中用@Value给属性配置文件中的值可以省略:
在这里插入图片描述

resources.properties配置文件中:
在这里插入图片描述

执行单元测试结果一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值