zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Spring boot] Read values from external properties file

SpringBoot File from Read properties VALUES External
2023-09-14 08:59:14 时间

Let's say we have a extral app.proporites file which contains some extra configuration:

// resources/app.properties
external.url="http://somedomain.com"

 

We can read the extra propoties by using @Value("${xxx}")

package com.example.in28minutes.properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SomeExternalService {

    @Value("${external.url}")
    private String url;

    public String returnServiceURL () {
        return url;
    }
}

 

As you can see, we didn't define where should we looking for "app.proporties" file, this is what we should do in main file by @PropertySource("")

package com.example.in28minutes;

import com.example.in28minutes.properties.SomeExternalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
@PropertySource("app.properties")
public class In28minutesPropotiesApplication {

    private static Logger LOGGER = LoggerFactory.getLogger(In28minutesPropotiesApplication.class);

    public static void main(String[] args) {
        // Application Context
        ApplicationContext applicationContext =
                SpringApplication.run(In28minutesPropotiesApplication.class, args);
        SomeExternalService someService = applicationContext.getBean(SomeExternalService.class);

        LOGGER.info("{}", someService.returnServiceURL());
    }
}