读取Springboot的三种方式

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;

}

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。