了解过spring-Boot这个技术的,应该知道Spring-Boot的核心配置文件application.properties,当然也可以通过注解自定义配置文件的信息。
Spring-Boot读取配置文件的方式:
一.读取核心配置文件信息application.properties的内容
核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单。
核心配置文件application.properties内容如下:
- test.msg=Hello World SpringBoot
方式一:使用@Value方式(常用)
- package Solin.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 WebController {
- @Value("${test.msg}")
- private String msg;
-
- @RequestMapping("/index1")
- public String index1(){
- return "方式一:"+msg;
- }
- }
注意:在@Value的${}中包含的是核心配置文件中的键名。在Controller类上加@RestController表示将此类中的所有视图都以JSON方式显示,类似于在视图方法上加@ResponseBody。
访问:http://localhost:8088/index1时得到:"方式一:Hello World SpringBoot"
方式二:使用Environment方式
- package Solin.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 WebController {
- @Autowired
- private Environment env;
-
- @RequestMapping("/index2")
- public String index2(){
- return "方式二:"+env.getProperty("test.msg");
- }
- }
注意:这种方式是依赖注入Evnironment来完成,在创建的成员变量private Environment env上加上@Autowired注解即可完成依赖注入,然后使用env.getProperty("键名")即可读取出对应的值。
访问:http://localhost:8088/index2时得到:"方式二:Hello World SpringBoot"
二.读取自定义配置文件信息,例如:author.properties
为了不破坏核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources
目录下创建配置文件author.properties
resources/author.properties
内容如下:
- author.name=Solin
- author.age=22
创建管理配置的实体类:
- package Solin.controller;
-
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.stereotype.Component;
-
-
- @Component
- @ConfigurationProperties(prefix = "author",locations = "classpath:author.properties")
- public class MyWebConfig{
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
注意:
在@ConfigurationProperties注释中有两个属性:
locations:指定配置文件的所在位置
prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以author.开头)
使用@Component是让该类能够在其他地方被依赖使用,即使用@Autowired注释来创建实例。
创建测试Controller
- package Solin.controller;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- @Controller
- public class ConfigController {
- @Autowired
- private MyWebConfig conf;
-
- @RequestMapping("/test")
- public @ResponseBody String test() {
- return "Name:"+conf.getName()+"---"+"Age:"+conf.getAge();
- }
- }
注意:由于在Conf类上加了注释@Component,所以可以直接在这里使用@Autowired来创建其实例对象。
读取核心配置文件
核心配置文件是指在resources根目录下的application.properties
或application.yml
配置文件,读取这两个配置文件的方法有两种,都比较简单。
核心配置文件application.properties
内容如下:
server.port=9090
test.msg=Hello World Springboot!
@RestController
public class WebController {
@Value("${test.msg}")
private String msg;
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index() {
return "The Way 1 : " +msg;
}
}
注意:在@Value
的${}中包含的是核心配置文件中的键名。在Controller类上加@RestController
表示将此类中的所有视图都以JSON方式显示,类似于在视图方法上加@ResponseBody
。
访问:http://localhost:9090/index 时将得到The Way 1 : Hello World Springboot!
@RestController
public class WebController {
@Autowired
private Environment env;
@RequestMapping(value = "index2", method = RequestMethod.GET)
public String index2() {
return "The Way 2 : " + env.getProperty("test.msg");
}
}
注意:这种方式是依赖注入Evnironment
来完成,在创建的成员变量private Environment env
上加上@Autowired
注解即可完成依赖注入,然后使用env.getProperty("键名")
即可读取出对应的值。
访问:http://localhost:9090/index2 时将得到The Way 2 : Hello World Springboot!
读取自定义配置文件
为了不破坏核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources/config
目录下创建配置文件my-web.properties
resources/config/my-web.properties
内容如下:
web.name=zslin
web.version=V 1.0
web.author=393156105@qq.com
创建管理配置的实体类:
@ConfigurationProperties(locations = "classpath:config/my-web.properties", prefix = "web")
@Component
public class MyWebConfig {
private String name;
private String version;
private String author;
public String getAuthor() {
return author;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public void setAuthor(String author) {
this.author = author;
}
public void setName(String name) {
this.name = name;
}
public void setVersion(String version) {
this.version = version;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
注意:
创建测试Controller
@RestController
@RequestMapping(value = "config")
public class ConfigController {
@Autowired
private MyWebConfig myWebConfig;
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index() {
return "webName: "+myWebConfig.getName()+", webVersion: "+
myWebConfig.getVersion()+", webAuthor: "+myWebConfig.getAuthor();
}
}
注意:由于在MyWebConfig类上加了注释@Component
,所以可以直接在这里使用@Autowired
来创建其实例对象。
访问:http://localhost:9090/config/index 时将得到webName: zslin, webVersion: V 1.0, webAuthor: 393156105@qq.com
示例代码:https://github.com/zsl131/spring-boot-test/tree/master/study02
在实际开发中,本地开发、测试服务、正式服务的配置信息有的地方是不一样的;比如本地测试log级别可能是debug,而正式环境下则为info;再比如数据库的配置,正式环境下和测试环境下是不一样的。以前我们通过手动更改这些配置来完成测试到正式的转移,但这样做还是有一定的风险,如果手动配置错误,则会导致很多错误。
Springboot给我们提供了一种方式,能够自动的切换正式环境配置及测试环境配置,下面就用一个小例子来演示一下如何进行配置信息的切换。
1、项目结构
上面这张图是这个小例子项目的结构,通过Maven来构架出一个Springboot项目:
1. Application.java : 这个文件是Springboot的启动类,项目的启动是执行这个文件中的main方法。
2. HelloController.java : 这个文件是我们测试的一个请求Controller。
3. application.properties : Springboot项目启动读取的配置信息文件。
4. application-release.properties : 正式环境下使用的配置信息文件。
5. application-stage.properties : 测试环境下使用的配置信息文件。
6. logback-dev.xml : 正式环境下的log配置文件。
7. logback-stage.xml : 测试环境下的log配置文件。
2、配置文件
2.1 application.properties
# 服务端口
server.port=8081
# 激活哪个环境下的配置
spring.profiles.active=stage
Springboot的启动文件中这里我们只放置了两项配置,在实际使用中,该文件放置一些正式环境、测试环境都会用到的共同配置信息即可;这里着重讲解一下spring.profiles.active
,这个配置项主要用于告诉服务使用哪个环境的配置,值为application-{profile}.properties
格式文件中的profile值,我们这个项目中值为:release、stage。
2.2 application-dev.properties
# 日志配置
logging.config=classpath:logback-release.xml
# 正式数据库配置
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = 000000
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
该文件是正式环境下使用的配置信息文件,这里我们配置了使用的log日志配置文件、数据库配置。
2.3 application-stage.properties
# 日志配置
logging.config=classpath:logback-stage.xml
# stage数据库配置
spring.datasource.url = jdbc:mysql://localhost:3306/test_2
spring.datasource.username = root
spring.datasource.password = 000000
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
该文件是测试环境下使用的配置信息文件,这里我们配置了使用的log日志配置文件、数据库配置。
3、启动类
@SpringBootApplication
@Controller
@ComponentScan(basePackages={"com.test.spring.boot.controller"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@ComponentScan(basePackages={“com.test.spring.boot.controller”}) 这行配置信息含义是:设置了自动扫描的包路径,即会扫描controller包下的bean,若有多个扫描包路径,可以以逗号分隔。
4、测试
4.1 HelloController
@RestController
public class HelloController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "Hello " + getUsername();
}
private String getUsername() {
String url = "select * from tb_user where id = ?";
UserBean userBean = jdbcTemplate.query(url, new Object[]{1}, new ResultSetExtractor<UserBean>(){
@Override
public UserBean extractData(ResultSet resultSet) throws SQLException, DataAccessException {
UserBean bean = new UserBean();
while(resultSet.next()) {
bean.setId(resultSet.getInt("id"));
bean.setUsername(resultSet.getString("username"));
bean.setPhone(resultSet.getString("phone"));
}
return bean;
}
});
return userBean.getUsername();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
这个Controller实现了一个REST的请求,访问 http://localhost:8081/hello可以请求到该Controller中,并访问数据库,查询到用户名,返回到客户端。
我们通过修改spring.profiles.active
参数,访问测试数据库、正式数据库,以此来验证是否切换了不同的环境配置文件。
4.2 开始测试
正式数据库中用户名为:test_1,测试数据库中用户名为:test_2
1、当spring.profiles.active
配置为stage,访问http://localhost:8081/hello:
2、当spring.profiles.active
配置为release,访问http://localhost:8081/hello:
大家可以动手测试测试,spring.profiles.active
这个配置项不仅可以在application.properties
文件中进行配置,还可以通过 java -jar 启动服务时添加到后面作为启动参数;这样也能够告诉服务使用哪个配置文件。
具体做法: