Are these lines with static initializers guaranteed to run in order? Because if not then things might go wrong
public Class x {
private static final BasicDataSource ds = new BasicDataSource();
private static final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
private static final SomeDao someDao = new SomeDao(jdbcTemplate);
}
Okay... How about this?
public Class x {
private static final BasicDataSource ds;
private static final JdbcTemplate jdbcTemplate;
private static final SomeDao someDao;
static {
ds = new BasicDataSource();
ds.setStuff("foo");
ds.setAnotherProperty("bar");
jdbcTemplate = new JdbcTemplate(ds);
SomeDao someDao = new SomeDao(jdbcTemplate);
}
}
They will be executed in sequential order corresponding to how they were listed in the source code.
This can be observed using in the following code:
For which the output is always
012345
.