读取Springboot的三种方式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读取Springboot的三种方式相关的知识,希望对你有一定的参考价值。
参考技术A 1.通过Value注解<code>
package com.hengan.springboottest.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController
//读取配置文件
@Value("$user.uname")
private Stringuname;
@RequestMapping("/method1")
public String getProp()
return "读取配置文件的第一种方式:通过Value注解 "+uname;
</code>
2.通过Environment类
```
package com.hengan.springboottest.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController
@Autowired
private Environmentenv;
@RequestMapping("/method2")
public String getProp2()
return "读取配置文件的第二种方式Env: "+env.getProperty("user.uname");
```
3.通过配置实体类
```
package com.hengan.springboottest.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController
@Autowired
private ReadConfFilereadConfFile;
@RequestMapping("/method3")
public ReadConfFile getProp3()
return readConfFile;
```
```
package com.hengan.springboottest.controller;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
//用@Data省去了getter,setter
@Data
//@ToString注解免去了手动写toString方法
@ToString
//是否当前缀不符合时抛出异常
@ConfigurationProperties(prefix ="user",ignoreUnknownFields =false)
@PropertySource("classpath:")
//声明一个组件
@Component
public class ReadConfFile
private Stringuname;
private Stringpwd;
private Stringage;
private Stringaddr;
private Stringsex;
```
以上是关于读取Springboot的三种方式的主要内容,如果未能解决你的问题,请参考以下文章