Boost Your Java Backend: Practical Coding Habits and Best Practices
This article shares a collection of practical Java/Spring coding habits—including using @ConfigurationProperties for YAML configs, Lombok's @RequiredArgsConstructor, modular method design, avoiding null returns, leveraging HashSet for fast lookups, fine‑grained locking, structured cache naming, @Cacheable with TTL, and asynchronous task handling—to help developers write cleaner, more maintainable, and higher‑performance backend code.
Define Configuration File
Store common variables in a YAML file and bind them with @ConfigurationProperties instead of using @Value.
@Data
// Specify prefix
@ConfigurationProperties(prefix = "developer")
@Component
public class DeveloperProperty {
private String name;
private String website;
private String qq;
private String phoneNumber;
}Inject the bean where needed:
@RestController
@RequiredArgsConstructor
public class PropertyController {
private final DeveloperProperty developerProperty;
@GetMapping("/property")
public Object index() {
return developerProperty.getName();
}
}Use @RequiredArgsConstructor Instead of @Autowired
Prefer constructor injection for beans; Lombok's @RequiredArgsConstructor generates the constructor automatically.
Code Modularization
Keep each method under 50 lines, focusing on a single responsibility, making it reusable across different features.
Throw Exceptions Instead of Returning Error Codes
Replace scattered return statements with meaningful exceptions to keep the code flow clean.
Prefer HashSet Over List for Existence Checks
Use HashSet for O(1) look‑ups instead of linear scans on a List.
HashSet<String> set = new HashSet<>();
// check if "a" exists
int index = hash(a);
return getNode(index) != null; // O(1)Granular Locking
Avoid large synchronized methods; use ReentrantLock or ReentrantReadWriteLock with the smallest possible critical section.
Cache Naming Conventions
Use concise, hierarchical keys such as module:submodule:entity for easy cache inspection.
@Cacheable with Expiration
Configure @Cacheable caches with explicit TTL to prevent stale data.
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
return new RedisCacheManager(
RedisCacheWriter.lockingRedisCacheWriter(factory),
this.getRedisCacheConfigurationWithTtl(1),
this.getRedisCacheConfigurationMap()
);
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer hour) {
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(om);
return RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
.entryTtl(Duration.ofHours(hour));
}Asynchronous Tasks
Offload time‑consuming operations to asynchronous tasks or message queues to improve API response time.
Additional Tips
Use Collection<T> for method parameters to accept any collection type.
Prefer Map<K,V> over concrete implementations when possible.
When syncing large data sets, use temporary tables to avoid locking the main table.
Read open‑source code to learn design patterns and advanced APIs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
