版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/cms18374672699/article/details/87607715
史上最简单Spring Boot教程:第二篇Spring Boot自定义属性及属性封装类(二)
转载请标明出处:https://blog.csdn.net/cms18374672699/article/details/87607715
在使用spring boot过程中,可以发现项目中只需要极少的配置就能完成相应的功能,这归功于spring boot中的模块化配置,在pom.xml中依赖的每个Starter都有默认配置,而这些默认配置足以满足正常的功能开发。
一、SpringBoot自定义属性
我直接把项目的application.properties文件改成application.yml文件
在项目HelloController中自定义application.yml文件中的属性
@Controller
public class HelloController {
@Value("${mysql.driver}")
private String dirver;
@Value("${mysql.url}")
private String url;
@Value("${mysql.username}")
private String username;
@Value("${mysql.password}")
private String password;
@ResponseBody
@RequestMapping("/mysql1")
public String mysql1(){
return this.dirver+"</br>"+this.url+"</br>"+this.username+"</br>"+this.password;
}
}
运行项目 :http://localhost:8081/springboot/mysql1 ,application.yml文件中的消息就打印出来了
二、SpringBoot属性封装类
新建MysqlEntity类文件,所有的文件都要放在com.examole.springboot01的文件下,不然运行项目会出现错误信息
定义属性封装类
我们可以看到上面报红Spring Boot Configuration Annotation Processor not found in classpass
点击右上角,在pom.xml文件中添加pom依赖,解决报红问题
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
添加controler层的Java代码进行测试
@Controller
public class HelloController {
@Resource
private MysqlEntity mysqlEntity;
@ResponseBody
@RequestMapping("/mysql2")
public MysqlEntity mysql2(){
return this.mysqlEntity;
}
}
运行项目 :http://localhost:8081/springboot/mysql2 ,application.yml文件中的新消息就打印出来了