[Java] Get data from DB using singleton service in Spring (Boot)

Get data from DB using singleton service in Spring (Boot)

・ DI for enum ・ Memory saving ・ Supports high load with cache function ・ Read only ・ I use it for ranking etc. ・ Supports both Spring Framework and Spring Boot ・ For mappers, please read and set as appropriate. -Initialize when updating context


・ Spring Framework 4.2.9 ・ Spring Boot 2.2.1 · Java 1.8 ・ Windows 10 64bit

SampleRankingSingletonService · Singleton service (enum) that retrieves and retains data -I want to DI mapper with @Autowired, but I can't, so create a separate initialization service. -I think it would be better to add a program to process the data. (Issuing SQL is a heavy load)

public enum SampleRankingSingletonService {


	//Read timeout value adjustment
	public static final int TIMEOUT_SEC = 1800;

	private static final Object lock = new Object();

	private LocalDateTime queryDate;

	//Latest ranking
	private List<Sample> latestRanking = new CopyOnWriteArrayList<>();

	private SampleMapper sampleMapper;

	private SampleRankingSingletonService () {

	public static SampleRankingSingletonService getInstance() {
		return INSTANCE;

	private boolean isTimeout() {
		LocalDateTime execDate = LocalDateTime.now();
		if (queryDate == null) { return true; }

		LocalDateTime expireDate = queryDate.plusSeconds(TIMEOUT_SEC);
		if (expireDate.isBefore(execDate)) {
			return true;
		return false;

	public synchronized void reload() {
		queryDate = LocalDateTime.now();
		latestRanking = sampleMapper.selectLatestRanking(); // <-Ranking acquisition SQL issuance

	//Call before performing data processing
	public void initQuery() {
		synchronized(lock) {
			if (isTimeout() || latestRanking.size() <= 0) {

	public Integer countLatestRanking() {
		return latestRanking.size();

SampleRankingSingletonInitializerService ・ Automatically generated by DI

public class SampleRankingSingletonInitializerService {

	private SampleMapper sampleMapper;

	//Set the DI mapper in the singleton service when generating the bean
	public void init() {

	//Execute the first query when updating the context(Spring Boot gives an error when running with PostConstruct)       
	public void onContextRefreshedEvent(ContextRefreshedEvent evt) {

	public SampleMapper getSampleMapper() {
		return sampleMapper;

	public void setSampleMapper(SampleMapper sampleMapper) {
		this.sampleMapper = sampleMapper;

XML file for DI

    <bean id="sample.sampleRankingSingletonInitializerService" class="org.sample.SampleRankingSingletonInitializerService">
        <property name="sampleMapper" ref="sample.SampleMapper" />

It is OK if you set a breakpoint, stop properly after starting the server, and get the data. Thank you for your hard work!

Recommended Posts

[Java] Get data from DB using singleton service in Spring (Boot)
Get weather forecasts from Watson Weather Company Data in simple Java
Get error information using DefaultErrorAttributes and ErrorAttributeOptions in Spring Boot 2.3
Data processing using stream API from Java 8
Exists using Specification in Spring Data JPA
Using JavaScript from Java in Rhino 2021 version
ERRORCODE = -4471 occurs in Java application using Db2.
Create Java Spring Boot project in IntelliJ
Get history from Zabbix server in Java
Automatically deploy a web application developed in Java using Jenkins [Spring Boot application]
Try to get data from database using MyBatis in Micronaut + Kotlin project
GetInstance () from a @Singleton class in Groovy from Java
Try calling the CORBA service from Spring (Java)
How to get Class from Element in Java
Get unixtime (seconds) from ZonedDateTime in Scala / Java
Java tips-Create a Spring Boot project in Gradle
◆ Get API created by Spring Boot from React
[Java] Get KFunction from Method / Constructor in Java [Kotlin]
[Spring Boot] How to get properties dynamically from a string contained in a URL
Sample code for DB control by declarative transaction in Spring Boot + Spring Data JPA
Create a portfolio app using Java and Spring Boot
Delete All from Java SDK in Azure Cosmos DB
Test field-injected class in Spring boot test without using Spring container
Get cookies in Spring
[Java] Deploy the Spring Boot application to Azure App Service
How to call and use API in Java (Spring Boot)
Easily get an integer from a system property in Java
Get attributes and values from an XML file in Java
CData Software Hands-on (Get Twitter data from Java console application)
I tried to get started with Swagger using Spring Boot
8 things to insert into DB using Spring Boot and JPA
Get a non-empty collection from an Optional stream in java
How to control transactions in Spring Boot without using @Transactional
Set context-param in Spring Boot
Try Spring Boot from 0 to 100.
Importing Excel data in Java 2
Spring Boot 2 multi-project in Gradle
[Java] Thymeleaf Basic (Spring Boot)
[Java] Get KClass in Java [Kotlin]
Import Excel data in Java
CICS-Run Java application-(4) Spring Boot application
Using Mapper with Java (Spring)
Spring Boot DB related tips
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Importing Excel data in Java 3
Try using Spring Boot Security
Using Docker from Java Gradle
[Java] [Spring] Spring Boot 1.4-> 1.2 Downgrade Note
Spring Boot DB connection pool
I tried to create an API to get data from a spreadsheet in Ruby (with service account)
[Java] Get date information 10 days later using milliseconds in the Date class
Get a proxy instance of the component itself in Spring Boot
Uploading and downloading files using Ajax in Spring Boot (without JQuery)
Fitted in Spring Boot using a bean definition file named application.xml
Compare Hello, world! In Spring Boot with Java, Kotlin and Groovy
What I did in the migration from Spring Boot 1.4 series to 2.0 series
What I did in the migration from Spring Boot 1.5 series to 2.0 series
How to get and add data from Firebase Firestore in Ruby
Unknown error in line 1 of pom.xml when using Spring Boot in Eclipse
Spring Boot + Java + GitHub authentication login