【问题标题】:why PropertySourcesPlaceholderConfigurer ignores value from property file为什么 PropertySourcesPlaceholderConfigurer 忽略属性文件中的值
【发布时间】:2018-04-11 09:20:37
【问题描述】:

在 SpringBoot 中,为了建立数据库连接,我将数据库属性放在属性文件中

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>

【问题讨论】:

标签: java spring-boot properties-file


【解决方案1】:

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

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

根据设计,环境变量在来自捆绑的 @PropertySource 的值之前考虑

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

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

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

见上面的链接。这与哪些属性无关,而只是定义属性的位置。

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2013-05-22
    • 2014-07-10
    • 2012-05-13
    相关资源
    最近更新 更多