为什么PropertySourcesPlaceholderConfigurer忽略属性文件中的值

时间:2018-04-11 09:20:38

标签: java spring-boot properties-file

在SpringBoot中,为了设置数据库连接,我将DB属性放在属性文件

mysql.properties

driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/musicdb?useSSL=true
username = prospring5
password = prospring5

还提供了配置文件

MysqlConfig.java

package pl.boot.music;

import java.sql.Driver;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

@Configuration
@PropertySource("classpath:mysql.properties")
public class MysqlConfig {

    private static Logger logger = LoggerFactory.getLogger(MysqlConfig.class);

    @Value("${driverClassName}")
    private String driverClassName;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

    @Lazy
    @Bean
    public DataSource dataSource() {
        try {
            SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
            @SuppressWarnings("unchecked")
            Class<? extends Driver> driver = (Class<? extends Driver>) Class.forName(driverClassName);
            dataSource.setDriverClass(driver);

            logger.debug("url = {" + url + "}");
            dataSource.setUrl(url);
            logger.debug("username = {" + username + "}");
            dataSource.setUsername(username);
            logger.debug("password = {" + password + "}");
            dataSource.setPassword(password);

            return dataSource;
        } catch (Exception e) {
            return null;
        }
    }
}

(不需要静态PropertySourcesPlaceholderConfigurer bean,SpringBoot自动包含文件)

现在,当我尝试测试如下:

MusicBootApplicationTests.java

package pl.boot.music;

import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
public class MusicBootApplicationTests {

    private static Logger logger = LoggerFactory.getLogger(MusicBootApplicationTests.class);

    @Test
    public void testDataSource() throws SQLException {
        GenericApplicationContext ctx = new AnnotationConfigApplicationContext(MysqlConfig.class);
        DataSource dataSource = ctx.getBean("dataSource", DataSource.class);
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            PreparedStatement statement = connection.prepareStatement("SELECT 1");
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                int mockVal = resultSet.getInt("1");
                assertTrue(mockVal == 1);
            }
            statement.close();
        } catch (SQLException e) {
            logger.debug("Something unexpected happened.", e);
            throw e;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                }
            }
            ctx.close();
        }
    }
}

分配给@Value(“$ {username}”)的值来自操作系统 - 而不是属性文件......

11:02:43.202 [main] DEBUG p.s.b.m.MysqlConfig - url = {jdbc:mysql://localhost:3306/musicdb?useSSL=true}
11:02:43.212 [main] DEBUG p.s.b.m.MysqlConfig - username = {Przemysław Lastname}
11:02:43.212 [main] DEBUG p.s.b.m.MysqlConfig - password = {prospring5}
11:02:43.454 [main] DEBUG p.s.b.m.MusicBootApplicationTests - Something unexpected happened.
java.sql.SQLException: Access denied for user 'Przemysław Lastname'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)

当然,我可以为我的“用户名”属性选择另一个名称来解决这个问题,但问题有点广泛:

1)为什么属性文件中的值不会覆盖环境中的值?

2)如何强制spring-boot通过属性文件中的属性覆盖环境中的值?

3)我在哪里可以找到“环境属性”列表,这些属性不能被属性文件中的值替换?

的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>pl.boot.music</groupId>
    <artifactId>preliminary</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>MusicBoot</name>
    <description>Music DB Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1 个答案:

答案 0 :(得分:0)

请查看:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

  

1)为什么属性文件中的值不会覆盖环境中的值?

按设计,在捆绑的@PropertySource

的值之前考虑环境变量
  

2)如何强制spring-boot通过属性文件中的属性覆盖环境中的值?

通过从环境中删除它,但更有可能在命令行上指定值。如果这是一个单元测试,请使用@TestPropertySource,它几​​乎覆盖其他所有内容。

  

3)我在哪里可以找到&#34;环境属性列表&#34;哪个不能被属性文件中的值替换?

见上面的链接。它不是关于哪些属性,而是关于定义属性的位置。