GVKun编程网logo

spring-从application.properties文件内部读取环境变量(spring 读取环境变量)

14

本文将带您了解关于spring-从application.properties文件内部读取环境变量的新内容,同时我们还将为您解释spring读取环境变量的相关知识,另外,我们还将为您提供关于java–

本文将带您了解关于spring-从application.properties文件内部读取环境变量的新内容,同时我们还将为您解释spring 读取环境变量的相关知识,另外,我们还将为您提供关于java – Spring Boot集成测试无法到达application.properties文件、java – 从application.properties Spring Boot读取值、java – 替换application.properties以外的Spring属性文件中的环境变量、Scala读取application.properties文件内容的实用信息。

本文目录一览:

spring-从application.properties文件内部读取环境变量(spring 读取环境变量)

spring-从application.properties文件内部读取环境变量(spring 读取环境变量)

我在 application.properties 文件中指定了Spring属性。如何从环境变量填充这些属性?

这是我尝试过的方法,但似乎不起作用:

application.properties

spring.datasource.url=jdbc:postgresql://#{ systemProperties[''DATABASE_HOST'']}:5432/dbnamespring.datasource.username = postgresspring.datasource.password = postgres

答案1

小编典典

您可以使用与引用${...}语法相同的方式来引用环境属性。

在您的情况下:

spring.datasource.url=jdbc:postgresql://${DATABASE_HOST}:5432/dbname

java – Spring Boot集成测试无法到达application.properties文件

java – Spring Boot集成测试无法到达application.properties文件

我有一些使用@RestController注释的类,我正在尝试使用mockmvc类进行测试.端点从Web应用程序正确响应,但在运行测试时出现以下错误(来自IntelliJ IDEA):

java.lang.IllegalArgumentException: Could not resolve placeholder
'spring.data.rest.base-path' in string value "${spring.data.rest.base-path}/whatever"

这就是application.properties文件的样子:

spring.data.rest.base-path=/api
spring.profiles.active=dev
...

我还有一个名为application-dev.properties的文件,其中包含其他(不同的)属性.

这是测试类的注释方式:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest // Also tried: @WebAppConfiguration
@ActiveProfiles("dev")
// Also tried: @PropertySource("classpath:application.properties")
// Also tried: @TestPropertySource("classpath:application.properties")
public class MyRestControllerTest {
    ...
}

另一方面,这是REST控制器的实现方式(使用有问题的属性):

@RestController
@RequestMapping("${spring.data.rest.base-path}/whatever")
public class MyRestController {
    ...
}

这就是应用程序主类的外观:

@SpringBootApplication(scanBasePackages = {...})
@EnableJpaRepositories({...})
@EntityScan({...})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

最后,这是项目结构的(子集):

my-project
|_ src
   |_ java
   |  |_ com.example.x
   |     |_ controller
   |        |_ MyRestController.java
   |
   |_ test
   |  |_ com.example.x
   |     |_ controller
   |        |_ MyRestControllerTest.java
   |
   |_ resources
      |_ application.properties
      |_ application-dev.properties

我在整个网络上找到了几个问题的解决方案,但它们似乎都不适合我.

最佳答案
答案最终与Spring注释和IntelliJ配置无关,而是与mockmvc有关,特别是与测试’setUp上使用的类和方法mockmvcBuilders.standalonesetup有关.这不会使用应用程序的上下文,因此无法正确读取依赖于它的属性.

将其更改为mockmvcBuilders.webAppContextSetup后,(来自文档)

Build[s] a mockmvc instance using the given,fully initialized (i.e.,
refreshed) WebApplicationContext.

一切正常.对于集成测试,使用它更有意义,不是吗?

感谢您的所有时间和精力.很抱歉没有显示提到的setUp方法,但我没想到问题可能是由那里引起的.

java – 从application.properties Spring Boot读取值

java – 从application.properties Spring Boot读取值

我的 Spring启动应用程序具有以下应用程序结

> src

>主要

> java
>资源

> application.properties

这是我的application.properties文件:

logging.level.org.springframework=TRACE
logging.level.org.hibernate=ERROR
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#spring.resources.chain.cache=false
#spring.resources.chain.html-application-cache=false
#spring.headers.cache=false
language=java

我有一个类需要使用该语言= java属性.这就是我尝试使用它的方式:

public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

由于某种原因,该打印值始终为“null”!我也试过把它放在类声明之上:

@PropertySource(value = "classpath:application.properties")

解决方法

它可以通过多种方式实现,请参阅下文.

@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

要么

@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Autowired
    private Environment env;

    public void readproperty() {
        env.getProperty("language");
    }

}

java – 替换application.properties以外的Spring属性文件中的环境变量

java – 替换application.properties以外的Spring属性文件中的环境变量

Spring Boot将自动解析application.properties文件中的任何${ENV}占位符,以及相应的环境变量.

但是,当我通过Quartz配置的Propertiesfactorybean文件提供quartz.properties时,不会发生这种解决方案.

@Bean
public Properties getQuartzProperties() throws IOException {
    Propertiesfactorybean propertiesfactorybean = new Propertiesfactorybean();
    propertiesfactorybean.setLocation(new ClassPathResource("/quartz.properties"));
    propertiesfactorybean.afterPropertiesSet();
    return propertiesfactorybean.getobject();
}

有没有Spring方法在不使用外部库的情况下替换属性文件中的这些环境变量?

最佳答案
您可以声明一个新类来提供属性(使用@Configuration注释)并提及@PropertySource

@Configuration
@PropertySource("classpath:quartz.properties")
public class QuartzConfig {
      //...
}

通过这种方式,您的Spring启动应用程序可以根据需要读取任意数量的属性文件.

Scala读取application.properties文件内容

Scala读取application.properties文件内容

application.properties

application.properties文件位于resources目录下

lpf=123

#kudu.master=10.101.15.229,10.101.15.230,10.101.15.231
kudu.master=szbigdata01,szbigdata02,szbigdata03

health_assess_data_table=health_assess_data
group_health_assess_result_table=group_health_assess_result

base_tag_table=base_tag
rule_tag_map_table=rule_tag_map

ReadPropFileUtil

package org.fiend.scalatest.util

import java.io.FileInputStream
import java.util.Properties

object ReadPropFileUtil {
    def main(args: Array[String]): Unit = {
        //loadProperties()
        println(readProp("kudu.master"))
    }

    def readProp(name: String): String = {
        val properties = new Properties()
        val path = Thread
                .currentThread()
                .getContextClassLoader
                .getResource("application.properties")
                .getPath //文件要放到resource文件夹下
        properties.load(new FileInputStream(path))

        val propVal = properties.getProperty(name)
        if (null == propVal) {
            throw new NullPointerException("read properties key={" + name + "}  is null!")
        }

        propVal
    }

    def loadProperties(): Unit = {
        val properties = new Properties()
        val path = Thread
                .currentThread()
                .getContextClassLoader
                .getResource("application.properties")
                .getPath //文件要放到resource文件夹下
        properties.load(new FileInputStream(path))

        //如果ddd不存在,则返回第二个参数
        println(properties.getProperty("ddd", "没有值"))

        properties.setProperty("ddd", "123")//添加或修改属性值
        // 读取键为ddd的数据的值
        println(properties.getProperty("ddd"))

        println(properties.getProperty("lpf"))//读取键为ddd的数据的值
    }
}

 

今天关于spring-从application.properties文件内部读取环境变量spring 读取环境变量的讲解已经结束,谢谢您的阅读,如果想了解更多关于java – Spring Boot集成测试无法到达application.properties文件、java – 从application.properties Spring Boot读取值、java – 替换application.properties以外的Spring属性文件中的环境变量、Scala读取application.properties文件内容的相关知识,请在本站搜索。

本文标签: