Backend Development 8 min read

Master Spring Boot 3: 5 Real-World Cases & Code Samples

This article presents a curated collection of practical Spring Boot 3 examples—including JSON parsing, automatic database script execution, custom DataSource configuration, properties/YAML loading, and data binding with validation—complete with code snippets and configuration details for Java backend developers.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Boot 3: 5 Real-World Cases & Code Samples

Spring Boot 3 practical case collection (123 examples) provides ready‑to‑use code for common backend tasks.

JSON Parsing Tools

When parsing JSON strings you can use Jackson (direct injection or manual creation) or Gson. Spring Boot also offers a factory that automatically selects the appropriate parser.

<code>// Injection
@Resource
private ObjectMapper objectMapper;

// Manual creation
ObjectMapper mapper = new ObjectMapper();

// Gson example
Gson gson = new GsonBuilder().create();

// Factory usage
String json = """
{
  "name": "pack",
  "sex": "男",
  "age": 22,
  "idNo": "640522199303092164"
}
""";
JsonParser jsonParser = JsonParserFactory.getJsonParser();
Map<String, Object> ret = jsonParser.parseMap(json);
System.err.println(ret);
</code>

Output result:

<code>{name=pack, sex=男, age=22, idNo=640522199303092164}</code>

Factory internal implementation:

Executing Database Scripts

Define a bean to run SQL scripts automatically at startup.

<code>@Configuration
public class DatabaseScriptExecution {
    @Bean
    DataSourceScriptDatabaseInitializer databaseInitializer(DataSource dataSource) {
        DatabaseInitializationSettings settings = new DatabaseInitializationSettings();
        settings.setEncoding(StandardCharsets.UTF_8);
        settings.setSchemaLocations(List.of("classpath:db/db.sql", "optional:classpath:db/data.sql"));
        return new DataSourceScriptDatabaseInitializer(dataSource, settings);
    }
}
</code>

Spring Boot can also execute scripts via configuration:

<code>spring:
  sql:
    init:
      mode: always
      username: root
      password: xxxooo
      encoding: UTF-8
      schema-locations:
        - optional:classpath:db/schema.sql
      data-locations:
        - optional:classpath:db/data.sql
</code>

Custom DataSource Configuration

Use DataSourceBuilder to create a custom DataSource bean.

<code>@Configuration
public class DataSourceConfig {
    @Bean
    DataSource createDataSource() {
        return DataSourceBuilder.create()
            .type(HikariDataSource.class)
            .driverClassName("com.mysql.cj.jdbc.Driver")
            .url("jdbc:mysql://localhost:3306/ds2")
            .username("root")
            .password("xxxooo")
            .build();
    }
}
</code>

Supported connection‑pool implementations: Hikari, Tomcat JDBC Pool, Apache DBCP2, Oracle UCP, C3P0.

Properties & YAML Parsing

Load a properties file:

<code>PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
ClassPathResource resource = new ClassPathResource("user.properties");
List<PropertySource<?>> sources = loader.load("user", resource);
sources.forEach(source -> System.err.println(source.getName() + "@" + source.getSource()));
</code>

Result:

<code>user@{pack.name=pack, pack.version=1.0.0, pack.title=xxxooo}</code>

Load a YAML file similarly or define a bean:

<code>@Bean
YamlPropertiesFactoryBean yamlFactoryBean() {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(new ClassPathResource("user.yaml"));
    return factory;
}
</code>

Data Binding

Bind configuration properties to an object using Binder :

<code>StandardEnvironment env = new StandardEnvironment();
env.getPropertySources().addFirst(new SimpleCommandLinePropertySource("--pack.title=xxxooo", "--pack.version=1.0.0"));
Binder binder = Binder.get(env);
BindResult<App> result = binder.bind("pack", App.class);
System.err.println(result.get());
record App(String title, String version) {}
</code>

Bind request parameters:

<code>DataBinder binder = new DataBinder(new App());
PropertyValues values = new ServletRequestParameterPropertyValues(request);
binder.bind(values);
Object target = binder.getTarget();
</code>

Validate bound data:

<code>DataBinder binder = new DataBinder(new App());
binder.setValidator(validator);
binder.validate();
binder.getBindingResult().getFieldErrors().forEach(error ->
    System.err.println(error.getField() + " @ " + error.getDefaultMessage()));
public class App {
    @NotEmpty(message = "标题不能空")
    private String title;
    private String version;
}
</code>
BackendJavaDatabaseConfigurationJSONspring-boot
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.