了解过spring-Boot这个技术的,应该知道Spring-Boot的核心配置文件application.properties,当然也可以通过注解自定义配置文件的信息。


Spring-Boot读取配置文件的方式:

一.读取核心配置文件信息application.properties的内容

     核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单。


核心配置文件application.properties内容如下:



[java]  view plain  copy



1. test.msg=Hello World SpringBoot



方式一:使用@Value方式(常用)


[java]  view plain  copy

1. package Solin.controller;  
2.   
3. import org.springframework.beans.factory.annotation.Value;  
4. import org.springframework.web.bind.annotation.RequestMapping;  
5. import org.springframework.web.bind.annotation.RestController;  
6.   
7. @RestController  
8. public class WebController {  
9. @Value("${test.msg}")  
10. private String msg;  
11.       
12. @RequestMapping("/index1")   
13. public String index1(){  
14. return "方式一:"+msg;  
15.     }  
16. }


注意:在@Value的${}中包含的是核心配置文件中的键名。在Controller类上加@RestController表示将此类中的所有视图都以JSON方式显示,类似于在视图方法上加@ResponseBody。

访问:http://localhost:8088/index1时得到:"方式一:Hello World SpringBoot"



方式二:使用Environment方式


[java]  view plain  copy

1. package Solin.controller;  
2.   
3. import org.springframework.beans.factory.annotation.Autowired;  
4. import org.springframework.beans.factory.annotation.Value;  
5. import org.springframework.core.env.Environment;  
6. import org.springframework.web.bind.annotation.RequestMapping;  
7. import org.springframework.web.bind.annotation.RestController;  
8.   
9. @RestController  
10. public class WebController {  
11. @Autowired  
12. private Environment env;  
13.       
14. @RequestMapping("/index2")   
15. public String index2(){  
16. return "方式二:"+env.getProperty("test.msg");  
17.     }  
18. }

注意:这种方式是依赖注入Evnironment来完成,在创建的成员变量private Environment env上加上@Autowired注解即可完成依赖注入,然后使用env.getProperty("键名")即可读取出对应的值。

访问:http://localhost:8088/index2时得到:"方式二:Hello World SpringBoot"



二.读取自定义配置文件信息,例如:author.properties

为了不破坏核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources目录下创建配置文件author.propertiesresources/author.properties内容如下:

[java]  view plain  copy

1. author.name=Solin  
2. author.age=22


创建管理配置的实体类:

1. package Solin.controller;  
2.   
3. import org.springframework.boot.context.properties.ConfigurationProperties;  
4. import org.springframework.context.annotation.Configuration;  
5. import org.springframework.stereotype.Component;  
6.   
7. //加上注释@Component,可以直接在其他地方使用@Autowired来创建其实例对象  
8. @Component  
9. @ConfigurationProperties(prefix = "author",locations = "classpath:author.properties")     
10. public class MyWebConfig{  
11. private String name;  
12. private int age;  
13. public String getName() {  
14. return name;  
15.     }  
16. public void setName(String name) {  
17. this.name = name;  
18.     }  
19. public int getAge() {  
20. return age;  
21.     }  
22. public void setAge(int age) {  
23. this.age = age;  
24.     }  
25. }


注意:
    在@ConfigurationProperties注释中有两个属性:
locations:指定配置文件的所在位置
prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以author.开头)
    使用@Component是让该类能够在其他地方被依赖使用,即使用@Autowired注释来创建实例。

创建测试Controller

1. package Solin.controller;  
2.   
3. import org.springframework.beans.factory.annotation.Autowired;  
4. import org.springframework.stereotype.Controller;  
5. import org.springframework.web.bind.annotation.RequestMapping;  
6. import org.springframework.web.bind.annotation.ResponseBody;  
7.   
8. @Controller    
9. public class ConfigController {  
10. @Autowired  
11. private MyWebConfig conf;  
12.       
13. @RequestMapping("/test")   
14. public @ResponseBody String test() {  
15. return "Name:"+conf.getName()+"---"+"Age:"+conf.getAge();   
16.     }
  1. }  


注意:由于在Conf类上加了注释@Component,所以可以直接在这里使用@Autowired来创建其实例对象。



读取核心配置文件

核心配置文件是指在resources根目录下的application.propertiesapplication.yml配置文件,读取这两个配置文件的方法有两种,都比较简单。核心配置文件application.properties内容如下:

server.port=9090

test.msg=Hello World Springboot!
  • 使用

@Value

  • 方式(常用):
@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!

  • 使用

Environment

  • 方式
@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.propertiesresources/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;
    }
}

注意:

@ConfigurationProperties

  • 注释中有两个属性:

locations

  • :指定配置文件的所在位置

prefix

  • :指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以

web.

  • 开头)
  • 使用

@Component

  • 是让该类能够在其他地方被依赖使用,即使用

@Autowired

  • 注释来创建实例。
创建测试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、项目结构

springboot配置远程MySQL springboot远程读取配置文件_配置文件

上面这张图是这个小例子项目的结构,通过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

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();
    }
}

这个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:

springboot配置远程MySQL springboot远程读取配置文件_配置信息_02

2、当spring.profiles.active配置为release,访问http://localhost:8081/hello:

springboot配置远程MySQL springboot远程读取配置文件_springboot配置远程MySQL_03

大家可以动手测试测试,spring.profiles.active这个配置项不仅可以在application.properties文件中进行配置,还可以通过 java -jar 启动服务时添加到后面作为启动参数;这样也能够告诉服务使用哪个配置文件。



spring boot不同环境读取不同配置



具体做法:

springboot配置远程MySQL springboot远程读取配置文件_配置文件_04

  • 不同环境的配置设置一个配置文件,例如:dev环境下的配置配置在application-dev.properties中;prod环境下的配置配置在application-prod.properties中。
  • 在application.properties中指定使用哪一个文件

    1、application-dev.properties(dev环境下的配置)


    [plain]  view plaincopy
  1. profile = dev_envrimont  
  2. 2、application-prod.properties(prod环境下的配置)

1 profile = prod_envrimont

  • 3、application.properties

1 spring.data.mongodb.uri=mongodb://192.168.22.110:27017/myfirstMongodb 2 3 #spring.profiles.active 4 spring.profiles.active=dev

  • 4、Controller
[java]  
       view plain 
        copy 
       
1. @Autowired  
2. 2     private Environment env;  
3. 3           
4. 4     @RequestMapping("/testProfile")  
5. 5     public String testProfile(){  
6. 6         return env.getProperty("profile");  
7. 7     }

测试

  • 上述代码执行后的结果是:dev_envrimont和mongodb://192.168.22.110:27017/myfirstMongodb
  • 如果application.properties的配置改为:spring.profiles.active=prod,则结果是:prod_envrimont
  • 如果application.properties的配置改为:spring.profiles.active=prod,而application.properties中也配置了profile=xxx(不管该配置配置在spring.profiles.active=prod的上方还是下方),这个时候结果是:prod_envrimont
  • 如果application.properties的配置改为:spring.profiles.active=prod,而application.properties中也配置了profile=xxx(不管该配置配置在spring.profiles.active=prod的上方还是下方),但是application-prod.properties删掉了profile = prod_envrimont,这个时候结果是:xxx

结论:

  • 各个环境公共的配置写在application.properties中
  • 各个模块独有的配置配置在自己的application-{xxx}.properties文件中
  • 程序读取的时候优先读取application.properties中选中的profile的配置,若读不到才会从application.properties去读