How to access H2 table in Spring @PostConstruct?

Solution for How to access H2 table in Spring @PostConstruct?
is Given Below:

I have defined the H2 database as unit test source database.

<jdbc:embedded-database id="adminmaster" type="H2">
    <jdbc:script location="classpath:db/schemas.sql" encoding="UTF-8"/>
    <jdbc:script location="classpath:db/test_data.sql" encoding="UTF-8"/>

And config the datasource connection pool

<bean id="adminDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.h2.Driver"/>
    <property name="url" value="jdbc:h2:mem:adminmaster;MODE=MYSQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>

But the problem is that when I want to query some data in table XXX, I got:

Cause: org.h2.jdbc.JdbcSQLException: Table “XXX” not
found; SQL statement:

  public void init() {
    try {
      // here I tried to get data from database
    } catch (Exception e) {
      log.error("load db jar failed, error: {}", Throwables.getStackTraceAsString(e));

I found I can query data in the normal @Test methods, But when I tried to run Spring Test, the @PostConstruct method will throw an exception.

If you are trying to access data from your test database, Junit 4 has the annotations @Before (before each test) and @BeforeClass (only once)

Junit5 has more explicit annotations :
@BeforeEach and @BeforeAll

@PostConstruct only ensures that your bean is correctly initialized with all the dependencies. Not that the DB is ready for use 😉

If you are using another test library look at the equivalence. But if you are using Spring you are certainly using Junit.