0 课程地址
https://www.imooc.com/video/16718/0
1 读取配置文件demo
1.1 引入依赖
<!-- 加载配置文件,引入依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
1.2 添加配置文件
resource.properties
com.imooc.openresource.name=imooc
com.imooc.openresource.website=www.imooc.com
com.imooc.openresource.language=java
1.3 添加实体类bean
package com.example.demo.bean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; /** * Resource * * @author 魏豆豆 * @date 2020/11/21 */ @Configuration//会引入资源文件 @PropertySource(value="classpath:resource.properties")//引入资源文件的地址 @ConfigurationProperties(prefix = "com.imooc.openresource")//前缀 public class Resource { private String name; private String website; private String language; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
1.4 Controller类调用
package com.example.demo.son.democ; import com.example.demo.bean.Resource; import com.example.demo.tools.JSONResult; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * ResourceController * * @author 魏豆豆 * @date 2020/11/21 */ @RestController public class ResourceController { @Autowired//自动装配,通过该注解可以消除get和set方法 private Resource resource; @RequestMapping("/getResource") public JSONResult getResourceController(){ Resource bean = new Resource(); BeanUtils.copyProperties(resource,bean); return JSONResult.ok(bean); } }
1.5 打印
2 常用注解
@Configuration//会引入资源文件 @PropertySource(value="classpath:resource.properties")//引入资源文件的地址 @ConfigurationProperties(prefix = "com.imooc.openresource")//前缀
@Autowired//自动装配,通过该注解可以消除get和set方法
诸葛