drunkenfist
drunkenfist

Reputation: 3048

Fetching global values from database on application startup in Spring boot

I'm writing a Spring Boot / JPA application. I have some values which needs to be visible to the entire application and these values are located in a database. Where should I fetch these values? Should I fetch them in the class containing @SpringBootApplication?

And how do I make it visible to the application? I read that with Spring, we can use a @Bean class to hold global variables. Then do I have to map my @Entity class with a Bean class and autowire the Bean class where ever I want? I'm new to Spring / JPA, so I apologize if the question is basic.

Thanks.

Upvotes: 1

Views: 1523

Answers (1)

Neil McGuigan
Neil McGuigan

Reputation: 48287

Make a bean that is instantiated with your applicationContext, and use the init-method to run some code after it's instantiated.

A very off the top of my head solution:

In applicationContext.xml:

<bean class="com.example.DbConfigLoader" init-method="init">

A class to load a config entity at startup:

public class DbConfigLoader {

    @Autowired
    private DbConfigRepository repository;

    private DbConfig dbConfig;

    public void init(){
        dbConfig = repository.findOne(1L);
    }

    public DbConfig getDbConfig() {
        return dbConfig;
    }
}

A class representing your config:

@Entity
public class DbConfig {

    @Id
    private Long id;

    private String someSetting;

    public String getSomeSetting() {
        return someSetting;
    }
}

A Spring Data repository for easy database access:

public interface DbConfigRepository extends JpaRepository<DbConfig, Long> {
}

Upvotes: 2

Related Questions