今日已更新 280 条资讯 | 累计 40385 条内容
关于我们

Externalized config & property-source order

Ankit Verma 2026年09月07日 17:35 0 次阅读 来源:Dev.to

Why your settings don't live in your code Every application has settings that change depending on where it runs. The database URL on your laptop is not the one in production. The port the app listens on might be 8080 locally and something else inside a container. The API key you test with is not the real one. Externalized configuration is the simple idea that these settings live outside your compiled code — in a text file, an environment variable, or a command-line flag — so you can change them without recompiling. You write the code once; the settings travel separately and get slotted in when the app starts. You meet this the first time you deploy a Spring Boot app. It runs fine on your machine, you ship the exact same jar to a server, and it picks up a different database — without a single line of code changing. This article is about how Spring pulls that off, and the one question that trips everyone up: when the same setting is defined in two places, who wins? Spring's first job: build one big lookup table Before your code runs, Spring goes hunting for settings. It looks in files, it reads environment variables, it scans the command line — and it pours everything it finds into a single key/value lookup. Spring calls this lookup the Environment . Think of it as one flat dictionary: you ask it for a key like server.port , and it hands back a value like 8080 . Every setting your app could possibly care about ends up in here, no matter where it originally came from. The most common place to put settings is a file named application.properties , which Spring looks for automatically: server . port = 8080 app . greeting = Hello from the properties file Each line is one key and one value. Once Spring has read this file into the Environment, any part of your app can ask for those keys. Reading a value: the two ways in The quickest way to pull a value out is the @Value annotation. You put it on a field, and Spring fills that field in for you as it builds the object: @Compon

本文内容来源于互联网,版权归原作者所有
查看原文