SpringBoot注解把配置文件自动映射到属性和实体类实战

简介:讲解使用@value注解配置文件自动映射到属性和实体类

1、配置文件加载

方式一

1、Controller上面配置

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

2、增加属性

@Value("${test.name}")

private String name;

    文件上传修改示例:

    FileController.java:

    

 package net.xdclass.demo.controller;

 import java.io.File;
import java.io.IOException;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import net.xdclass.demo.domain.JsonData; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; /**
* 功能描述:文件测试
*
* <p> 创建时间:Apr 22, 2018 11:22:29 PM </p>
*/
@Controller
@PropertySource({"classpath:application.properties"})
public class FileController { @RequestMapping(value = "/api/v1/gopage")
public Object index() {
return "index";
} //private static final String filePath = "L:/Workspaces/Eclipse_Neon/txkt/SpringBootClass/xdclass_springboot/src/main/resources/static/images/";//末尾需要加/,这样才能写进来
//private static final String filePath = "L:/images/";//末尾需要加/,这样才能写进来 @Value("${web.file.path}")
private String filePath; @RequestMapping(value = "upload")
@ResponseBody
public JsonData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) { // file.isEmpty(); 判断图片是否为空
// file.getSize(); 图片大小进行判断 System.out.println("配置注入打印,文件路径为:" + filePath); String name = request.getParameter("name");
System.out.println("用户名:" + name); // 获取文件名
String fileName = file.getOriginalFilename();
System.out.println("上传的文件名为:" + fileName); // 获取文件的后缀名,比如图片的jpeg,png
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名为:" + suffixName); // 文件上传后的路径
fileName = UUID.randomUUID() + suffixName;
System.out.println("转换后的名称:" + fileName); File dest = new File(filePath + fileName); try {
file.transferTo(dest); return new JsonData(0, fileName);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new JsonData(-1, "fail to save ", null);
} }

    application.properties:

 web.images-path=L:/images
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}
#指定某些文件不进行监听,即不会进行热加载devtool(重启后不会监听下面这个文件)
#spring.devtools.restart.exclude=application.properties #通过触发器,去控制什么时候进行热加载部署新的文件
spring.devtools.restart.trigger-file=trigger.txt server.port=8083 #文件上传路径配置
web.file.path=L:/images #测试配置文件注入
test.name=www.xdclass.net
test.domain=springboot

    控制台结果:

      配置注入打印,文件路径为:L:/images

      用户名:123

      上传的文件名为:hongmi6.jpg

      上传的后缀名为:.jpg

      转换后的名称:ee4b60bd-35b4-4df6-bee6-ed62dd5e4a00.jpg

    浏览器返回值:

    {"code":0,"data":"ee4b60bd-35b4-4df6-bee6-ed62dd5e4a00.jpg","msg":null}

    方式二:实体类配置文件
步骤:

1、添加 @Component 注解;

2、使用 @PropertySource 注解指定配置文件位置;

3、使用 @ConfigurationProperties 注解,设置相关属性;

4、必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。

@Autowired

private ServerSettings serverSettings;

例子:

@Configuration

@ConfigurationProperties(prefix="test")

@PropertySource(value="classpath:resource.properties")

public class ServerConstant {

        代码示例:

        ServerSettings.java:

 package net.xdclass.demo.domain;

 import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component; //服务器配置
@Component
@PropertySource({"classpath:application.properties"})
//@ConfigurationProperties
//自动加入前缀,无需写入test.
@ConfigurationProperties(prefix="test")
//若不想使用prefix="test",前提是该类中定义的名称要与application.properties中定义的名称一致,即一一对应
public class ServerSettings { //名称
//使用prefix="test"后,无需再使用Value注解
//@Value("${name}")
private String name; //域名地址
//@Value("${domain}")
private String domain; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getDomain() {
return domain;
} public void setDomain(String domain) {
this.domain = domain;
} }

      application.properties同上一个示例

      GetController.java部分代码:

     @Autowired
private ServerSettings serverSettings;
@GetMapping("/v1/test_properties")
public Object testProperties(){
return serverSettings;
}

    浏览器测试:

    地址栏输入:http://localhost:8083/v1/test_properties

    结果:{"name":"www.xdclass.net","domain":"springboot"}

常见问题:

1、配置文件注入失败,Could not resolve placeholder

解决:根据springboot启动流程,会有自动扫描包没有扫描到相关注解,

默认Spring框架实现会从声明@ComponentScan所在的类的package进行扫描,来自动注入,

因此启动类最好放在根路径下面,或者指定扫描包范围

spring-boot扫描启动类对应的目录和子目录

2、注入bean的方式,属性名称和配置文件里面的key一一对应,就不用加@Value 这个注解

如果不一样,就要加@value("${XXX}") 

3、SpringBoot注解把配置文件自动映射到属性和实体类实战简介:讲解使用@value注解配置文件自动映射到属性和实体类1、配置文件加载方式一1、Controller上面配置   @PropertySource({"classpath:resource.properties"})2、增加属性 @Value("${test.name}") private String name;
方式二:实体类配置文件步骤:1、添加 @Component 注解;2、使用 @PropertySource 注解指定配置文件位置;3、使用 @ConfigurationProperties 注解,设置相关属性;
4、必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。@Autowired    private ServerSettings serverSettings;
    例子:    @Configuration@ConfigurationProperties(prefix="test")@PropertySource(value="classpath:resource.properties")public class ServerConstant {

常见问题:1、配置文件注入失败,Could not resolve placeholder解决:根据springboot启动流程,会有自动扫描包没有扫描到相关注解, 默认Spring框架实现会从声明@ComponentScan所在的类的package进行扫描,来自动注入,因此启动类最好放在根路径下面,或者指定扫描包范围spring-boot扫描启动类对应的目录和子目录2、注入bean的方式,属性名称和配置文件里面的key一一对应,就用加@Value 这个注解如果不一样,就要加@value("${XXX}")

SpringBoot注解把配置文件自动映射到属性和实体类实战的更多相关文章

  1. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_2-7.接口配置文件自动映射到属性和实体类配置

    笔记 7.接口配置文件自动映射到属性和实体类配置     简介:使用@value注解配置文件自动映射到属性和实体类 1.添加 @Component或者Configuration 注解:        ...

  2. SpringBoot配置文件自动映射到属性和实体类(8)

    一.配置文件加载 1.Controller中配置并指向文件 @Controller @PropertySource(value = { "application.properties&quo ...

  3. SpringBoot------注解把配置文件自动映射到属性和实体类

    1.映射到属性 package top.ytheng.demo.controller; import org.springframework.beans.factory.annotation.Valu ...

  4. 利用在线工具根据JSon数据自动生成对应的Java实体类

    如果你希望根据JSon数据自动生成对应的Java实体类,并且希望能进行变量的重命名,那么“JSON To Java”一定适合你.(下面的地址需要FQ) https://jsontojava.appsp ...

  5. T4 模板自动生成带注释的实体类文件

    T4 模板自动生成带注释的实体类文件 - 只需要一个 SqlSugar.dll 生成实体就是这么简单,只要建一个T4文件和 文件夹里面放一个DLL. 使用T4模板教程 步骤1 创建T4模板 如果你没有 ...

  6. EF自动创建数据库步骤之一(实体类写法)

    文章演示使用EF自动创建数据库第一个步骤创建实体类. 一.创建表映射实体类 using System; using System.Collections.Generic; using System.C ...

  7. springboot自定义属性文件与bean映射注入属性值

    主要有几点: 一.导入依赖 springboot的包和: <dependency> <groupId>org.springframework.boot</groupId& ...

  8. hibernate 数据库列别名自动映射pojo属性名

    package com.pccw.business.fcm.common.hibernate; import java.lang.reflect.Field; import java.math.Big ...

  9. T4 模板自动生成带注释的实体类文件 - 只需要一个 SqlSugar.dll

    生成实体就是这么简单,只要建一个T4文件和 文件夹里面放一个DLL. 使用T4模板教程 步骤1 创建T4模板 ,一定要自已新建,把T4代码复制进去,好多人因为用我现成的T4报错(原因不明) 点击添加文 ...

随机推荐

  1. BZOJ1030[JSOI2007]文本生成器——AC自动机+DP

    题目描述 JSOI交给队员ZYX一个任务,编制一个称之为“文本生成器”的电脑软件:该软件的使用者是一些低幼人群,他们现在使用的是GW文本生成器v6版.该软件可以随机生成一些文章―――总是生成一篇长度固 ...

  2. Assign the task HDU - 3974(dfs序+线段树)

    There is a company that has N employees(numbered from 1 to N),every employee in the company has a im ...

  3. 自学Linux Shell8.1-linux文件系统概述及操作

    点击返回 自学Linux命令行与Shell脚本之路 8.1-linux文件系统概述及操作 1. linux支持的文件系统 Windows常用的分区格式有三种,分别是FAT16.FAT32.NTFS格式 ...

  4. 洛谷 P2587 [ZJOI2008]泡泡堂 解题报告

    P2587 [ZJOI2008]泡泡堂 题目描述 第XXXX届NOI期间,为了加强各省选手之间的交流,组委会决定组织一场省际电子竞技大赛,每一个省的代表队由n名选手组成,比赛的项目是老少咸宜的网络游戏 ...

  5. P1856 矩形周长

    哇!这小破题坑了我好久. 扫描线+线段树 这题数据范围小,没离散化.真要离散化我还搞不好呢. 具体的看这个博客吧. 主要是这个坑爹的c,len把我搞了,其他的还好. 代码: #include < ...

  6. git branch 分支管理

    在多人协作的情况下,master通常是稳定的分支.可以再建一些"develop","testing"等名称的分支.主管master的人做开发的话最好也建立自己的 ...

  7. asp.net上传图片文件自动修改图片大小代码

    #region 图片缩放 /// <summary> /// 图片缩放 /// </summary> /// <param name="savePath&quo ...

  8. $\mathcal{FFT}$·$\mathcal{Fast \ \ Fourier \ \ Transformation}$快速傅立叶变换

    \(2019.2.18upd:\) \(LINK\) 之前写的比较适合未接触FFT的人阅读--但是有几个地方出了错,大家可以找一下233 啊-本来觉得这是个比较良心的算法没想到这么抽搐这个算法真是将一 ...

  9. 1032. Sharing (25)

    To store English words, one method is to use linked lists and store a word letter by letter. To save ...

  10. pyautogui_pdf批量转换为TXT

    pyautogui_pdf批量转换为TXT, 用pdf自带无损转换 # -*- coding: utf-8 -*- """ Created on Thu May 5 15 ...