In Java application development, choosing the right configuration file format and processing tools is crucial to improving development efficiency and system flexibility.
With the development of technology, the configuration file format has expanded from traditional Properties files to XML, JSON, YAML and other forms.
1. Java Properties API
Basic introduction
The Java Properties API is a built-in tool in JDK, specially designed for processing.properties
File, this is the most traditional and widely used configuration file format in Java.
Main features
- JDK native support, no additional dependencies required
- Simple key-value pair format
- Supports loading from files, input streams, and XML
- Provide default value mechanism
Example of usage
import ; import ; import ; public class PropertiesDemo { public static void main(String[] args) { Properties properties = new Properties(); // Load configuration from file try (FileInputStream fis = new FileInputStream("")) { (fis); // Read configuration items (provided default values) String dbUrl = ("", "jdbc:mysql://localhost:3306/mydb"); String username = ("", "root"); String password = ("", ""); ("Database URL: " + dbUrl); ("Username: " + username); ("Password: " + password); } catch (IOException e) { (); } } }
Applicable scenarios
- Simple application configuration
- International resource documents
- Traditional Java applications
- A system that requires backward compatibility
Pros and cons
advantage
- Simple and easy to use, low learning cost
- JDK built-in, no additional dependencies required
- Widely supported and used
shortcoming
- Hierarchical structure is not supported
- Limited data type support (mainly strings)
- Not suitable for complex configurations
2. Jackson (JSON processing)
Basic introduction
Jackson is one of the popular JSON processing libraries in the current Java ecosystem, providing complete JSON serialization and deserialization functions, which can easily handle JSON format configuration files.
Main features
- Complete JSON processing capabilities
- Strong object mapping capability
- Rich annotation support
- Modular design
- high performance
- Supports tree model and streaming
- Strong scalability, supports other formats such as YAML
Example of usage
import ; import ; import ; import ; public class JacksonConfigDemo { // Configuration class public static class AppConfig { private String name; private DatabaseConfig database; private boolean debugMode; private List<String> supportedTypes; // Getters and setters // ... } public static class DatabaseConfig { private String url; private String username; private String password; private int maxConnections; // Getters and setters // ... } public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(); try { // 1. Use object binding to read configuration AppConfig config = (new File(""), ); ("App Name: " + ); ("Debug Mode: " + ); ("Database URL: " + ); // 2. Read the configuration using the tree model JsonNode rootNode = (new File("")); String appName = ("name").asText(); boolean debugMode = ("debugMode").asBoolean(); JsonNode databaseNode = ("database"); String dbUrl = ("url").asText(); // 3. Update the configuration and save it = !; = 20; () .writeValue(new File(""), config); } catch (IOException e) { (); } } }
Applicable scenarios
- Complex configuration structure
- Applications that require object mapping
- Modern Web and Microservices Applications
- RESTful API configuration
- Unified configuration plan for front and back ends
Pros and cons
advantage
- Comprehensive and powerful
- high performance
- Powerful object mapping and type conversion
- Rich customization options
- Active community and documentation support
- Seamless integration with frameworks like Spring
shortcoming
- The API is more complex
- Full introduction will increase the dependency size
- More complex configuration
3. Apache Commons Configuration
Basic introduction
Apache Commons Configuration provides a unified interface to access configuration files in multiple formats, including Properties, XML, JSON, etc. It is a feature-rich configuration management library.
Main features
- Supports multiple configuration file formats
- Unified configuration interface
- Configure merges and hierarchies
- Automatic type conversion
- Support configuration reload and change notifications
Example of usage
import .; import .; import .; import .; import .; import .; public class CommonsConfigDemo { public static void main(String[] args) { try { // 1. Simple usage: Load the attribute file Configurations configs = new Configurations(); Configuration propConfig = (""); String appName = ("", "MyApp"); int maxThreads = ("-threads", 10); boolean debugMode = ("", false); ("Application Name: " + appName); ("Max Threads: " + maxThreads); ("Debug Mode: " + debugMode); // 2. Load and process JSON configuration Parameters params = new Parameters(); FileBasedConfigurationBuilder<JSONConfiguration> builder = new FileBasedConfigurationBuilder<>() .configure(() .setFileName("")); Configuration jsonConfig = (); String dbUrl = (""); String[] supportedFormats = ("-formats"); ("Database URL: " + dbUrl); ("Supported Formats:"); for (String format : supportedFormats) { ("- " + format); } // 3. Combining multiple configuration sources Configuration compositeConfig = new CombinedConfiguration(); ((CombinedConfiguration) compositeConfig).addConfiguration(propConfig); ((CombinedConfiguration) compositeConfig).addConfiguration(jsonConfig); } catch (ConfigurationException e) { (); } } }
Applicable scenarios
- Applications that require support for multiple configuration formats
- Complex configuration requirements
- A system that requires hot reloading
- Enterprise-level applications
Pros and cons
advantage
- Unified API processing multiple formats
- Rich feature set
- Flexible configuration combination
- Type-safe configuration access
shortcoming
- More complex than simple configuration
- Additional dependencies
- More complex configuration
4. SnakeYAML
Basic introduction
SnakeYAML is a Java library that processes YAML format files. YAML format is becoming more and more popular in modern application configurations due to its high human readability, support for comments, and clear hierarchy structure.
Main features
- YAML format support
- Supports complex data structures
- Conversion of Java Objects and YAML
- Support comments and citations
- Collection and mapping support
Example of usage
import ; import ; import ; import ; public class SnakeYAMLDemo { public static void main(String[] args) { Yaml yaml = new Yaml(); try { // 1. Load the YAML file to the Map Map<String, Object> config = (new FileInputStream("")); // Access nested configuration Map<String, Object> server = (Map<String, Object>) ("server"); int port = (int) ("port"); Map<String, Object> spring = (Map<String, Object>) ("spring"); Map<String, Object> profiles = (Map<String, Object>) ("profiles"); ("Server Port: " + port); ("Active Profile: " + ("active")); // 2. Map directly to custom classes ServerConfig serverConfig = ( new FileInputStream(""), ); ("Max Threads: " + ()); // 3. Handle multi-document YAML Iterable<Object> documents = (new FileInputStream("")); for (Object document : documents) { ("--- Document ---"); (document); } } catch (FileNotFoundException e) { (); } } // Configuration class public static class ServerConfig { private int port; private int maxThreads; private boolean ssl; // Getters and setters // ... public int getMaxThreads() { return maxThreads; } } }
Applicable scenarios
- Modern cloud native applications
- Complex configuration structure
- Projects that require human-readable configuration formats
- Kubernetes and Docker configuration
Pros and cons
advantage
- Strong readability
- Support complex data structures
- Support comments
- A concise way of representation
- Widely used in modern applications
shortcoming
- Sensitive to spaces
- Beginners may be prone to errors
- Sometimes parsing error messages is not clear enough
5. Spring Boot Configuration
Basic introduction
Spring Boot provides a powerful configuration management system that supports multiple configuration sources, configuration file hierarchies and attribute binding. This is one of the core features of building Spring Boot applications.
Main features
- Supports multiple configuration formats (Properties, YAML)
- Environment-specific configuration
- Configuration properties bound to Java objects
- Configuration attribute verification
- Loose binding rules (support different naming styles)
Example of usage
import ; import ; import ; import ; import ; import ; import ; import ; import ; @SpringBootApplication @EnableConfigurationProperties() public class SpringConfigDemo { public static void main(String[] args) { (, args); } @Bean public void displayConfig(ServerProperties serverProps) { ("Server Port: " + ()); ("Server Address: " + ()); ("Max Threads: " + ()); ("SSL Enabled: " + ()); } } @Component @ConfigurationProperties(prefix = "server") class ServerProperties { @Min(1000) @Max(65535) private int port = 8080; @NotEmpty private String address = "localhost"; private int maxThreads = 200; private boolean sslEnabled = false; // Getters and setters // ... }
:
server: port: 9090 address: 0.0.0.0 max-threads: 100 ssl-enabled: true
Applicable scenarios
- Spring Boot App
- Microservice architecture
- Applications that require a lot of configuration properties
- Multi-environment deployment
Pros and cons
advantage
- Seamless integration with Spring Boot
- Type-safe property binding
- Flexible configuration source support
- Environmental isolation
- Powerful verification function
shortcoming
Relying on the Spring ecosystem, not suitable for non-Spring applications
6. INI4J - INI file processing
Basic introduction
INI4J is a Java library specially designed for handling INI format configuration files. INI files are a simple configuration file format that uses sections and key-value pairs to organize data, which is still very practical in some scenarios.
Main features
- Complete support for INI file format
- Support sections and subsections
- Simple API
- Two-way operation (read and write)
- Support comments
- Type conversion function
Example of usage
import org.; import org.; import ; import ; public class Ini4jDemo { public static void main(String[] args) { try { // 1. Read the INI file Ini ini = new Ini(new File("")); // 2. Access sections and key values Section databaseSection = ("database"); String url = ("url"); String username = ("username"); String password = ("password"); ("Database URL: " + url); ("Username: " + username); // 3. Get value with type conversion int port = ("port", ); boolean ssl = ("ssl", ); ("Port: " + port); ("SSL: " + ssl); // 4. Modify the configuration ("max_connections", 20); ("timeout", 30); // 5. Add a new section Section loggingSection = ("logging"); ("level", "INFO"); ("file", "/var/log/"); // 6. Save configuration (new File("")); } catch (IOException e) { (); } } }
Example:
; Database configuration [database] url=jdbc:mysql://localhost:3306/mydb username=root password=secret port=3306 ssl=true ; Application settings [app] name=MyApplication version=1.0.0 debug=false
Applicable scenarios
- Simple configuration requirements
- Legacy system integration
- Windows Application Configuration
- User preferences
- Simple application settings
Pros and cons
advantage
- Simple and intuitive format
- Good readability for humans
- Lightweight
- Simple logic
- Widely supported, especially in Windows environments
shortcoming
- Complex data structures are not supported
- Lack of standardization
- Limited to simple key-value pairs and sections
7. Typesafe Config (Lightbend Config)
Basic introduction
Typesafe Config is a configuration library developed by Lightbend, which supports HOCON (Human-Optimized Config Object Notation), JSON and Properties formats.
It is widely used in projects such as Akka, Play Framework, etc.
Main features
- Supports HOCON format (superset of JSON)
- Powerful citation and replacement functions
- Configuration file merge
- Rich type conversion
- Support conditions including configuration
Example of usage
import ; import ; import ; import ; public class TypesafeConfigDemo { public static void main(String[] args) { // 1. Load configuration (automatically search, , ) Config config = (); // 2. Get the configuration of nested paths String dbUrl = (""); int dbPoolSize = (""); // 3. Use path replacement and reference String appLogDir = ("-dir"); String accessLogPath = ("-log"); // It can be defined as follows: // -log = ${-dir}"/" // 4. Convert to Java Map Config dbConfig = ("database"); Map<String, Object> dbMap = ().unwrapped(); // 5. Get all configuration keys for (<String, ConfigValue> entry : ()) { (() + " = " + ().render()); } // 6. Merge configuration Config defaultConfig = (""); Config customConfig = (new File("")); Config mergedConfig = (defaultConfig).resolve(); // 7. Type-safe time and memory size configuration timeout = (""); long maxMemory = ("-memory"); ("Timeout: " + () + " seconds"); ("Max Memory: " + (maxMemory / (1024 * 1024)) + " MB"); } }
Applicable scenarios
- Scala and Akka Projects
- Configurations that require references and variable replacement
- Complex configuration structure
- Modern reactive applications
Pros and cons
advantage
- Powerful HOCON format
- Flexible citations and replacements
- Good type support
- Support conditions include
shortcoming
- Not as widely used in the project as other libraries
- Configuration errors may be difficult to debug
- A relatively higher learning curve
Summarize
With the evolution of Java application architecture, the format and processing methods of configuration files are also constantly developing. From early Properties files, to XML, to the popular JSON and YAML, each format has its advantages and applicable scenarios.
Choosing the right configuration processing tool should consider the specific needs of the project, team familiarity, performance requirements, and future scalability.
No matter which tool you choose, good configuration management practices (such as hierarchical structure, environmental isolation, sensitive information processing) are the key to building robust and maintainable applications.
The above is the detailed explanation of the use of 7 tools in Java that handle various configuration files. For more information about Java processing configuration files, please pay attention to my other related articles!