(013)Spring Boot之启动时设置默认配置文件属性

  springboot中通常在application.properties文件中设置属性。也可以通过SpringApplication的setDefaultProperties方法设置属性,如下:

  pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.edu.spring</groupId>
    <artifactId>springboot</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>springboot</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.1.6.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

</project>
View Code

  App.java

package com.edu.spring.springboot;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;

public class App 
{
    
    @Value("${server.host:localhost}")
    private String serverhost;
    
    public static void main( String[] args)
    {
        SpringApplication app=new SpringApplication(App.class);
        
        Map<String,Object> map=new HashMap<>();
        map.put("server.host","127.0.0.1");
        app.setDefaultProperties(map);
        
        ConfigurableApplicationContext context= app.run(args);
        System.out.println(context.getBean(App.class).serverhost);

        context.close();
    }
}
View Code

  运行结果如下:

   如果在application.properties文件中设置相同的属性,最终获取的是配置文件中的属性,如下:

  application.properties

server.host=192.168.1.100
View Code

  运行结果如下:

猜你喜欢

转载自www.cnblogs.com/javasl/p/11918162.html