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. BZOJ[Usaco2017 Jan]Promotion Counting——线段树合并

    题目描述 The cows have once again tried to form a startup company, failing to remember from past experie ...

  2. BZOJ1775[USACO 2009 Dec Gold 3.Video Game Troubles]——DP

    题目描述 输入 * 第1行: 两个由空格隔开的整数: N和V * 第2到第N+1行: 第i+1行表示第i种游戏平台的价格和可以在这种游戏平台上面运行的游 戏.包含: P_i, G_i还有G_i对由空格 ...

  3. 睡前小dp-hdu3853-概率dp

    http://acm.hdu.edu.cn/showproblem.php?pid=3853 膜猴烧酒madoka 讲定义为dp[i][j] 位置为ij的魔法值期望,可以发现dp[i][j] = dp ...

  4. python 时间模块 -- time

    time 时间模块 和时间有关系的我们就要用到时间模块.在使用模块之前,应该先导入模块. # 常用方法 import time print("现在执行我") time.sleep( ...

  5. Codeforces925C Big Secret 【构造】【贪心】

    题目大意:给出异或差分序列,要你任意排列使得原序列递增. 题目分析: 我们在使得异或结果递增的过程中总能找到一个值使得它的最高位的1对应当前值的0.那么我们贪心的选择最高位最低的一个任意值使得它满足这 ...

  6. Hdoj 2187.悼念512汶川大地震遇难同胞——老人是真饿了 题解

    时间:2008年5月16日(震后第4天) 地点:汶川县牛脑寨 人物:羌族老奶奶 [转载整理]牛脑寨是一个全村600多人的羌族寨子,震后几天,这里依然能常常听到隆隆的声音,那是对面山上石头不断滑落的声音 ...

  7. JAVA实现邮件发送功能(账号注册验证码、账号激活等)

    第一步,导入JAR包,JAR包下载地址[http://pan.baidu.com/s/1kVRvGyF] 如果是Maven,请直接在Pom文件中加入 <dependency> <gr ...

  8. springboot集成druid连接池

    使用druid连接池主要有几步: 1.添加jar和依赖 <groupId>org.mybatis.spring.boot</groupId> <artifactId> ...

  9. 不跳转修改url(history.pushState)

    有时候我们会想不跳转的情况下修改url 直接上代码吧: history.pushState(null,"","?test=123") 值得注意的是,为了用户安全 ...

  10. thread join和detach的区别

    线程状态: 在一个线程的生存期内,可以在多种状态之间转换,不同的操作系统可以实现不同的线程模型,定义许多不同的线程状态,每个状态还可以包含多个子状态,但大体来说,如下几种状态是通用的: 1)就绪:参与 ...