Static Code Blocks
In a presentation that I gave recently, I noticed that some of the participants never heard of static code blocks before. Static code blocks let you execute something at class loading time (assign a value for example). They are like “Class-Constructors”. In this example i created a @Default-Configuration
-annotation. Once the Application was loaded, the static code block was looking for the annotation and set the default configuration (a property-file)
The annotation:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ TYPE, METHOD, FIELD, PARAMETER })
public @interface DefaultConfiguration {
}
The annotated method:
public class Configurator {
public void setConfigTest() {
AppConfig.loadProperties("ConfigTest.properties");
}
public void setConfigDev() {
AppConfig.loadProperties("ConfigDev.properties");
}
@DefaultConfiguration
public void setConfigProduction() {
AppConfig.loadProperties("ConfigProduction.properties");
}
}
The configuriation entry point of the application:
public class AppConfig {
private static Properties properties;
static {
AppConfig.initDefaultConfig();
}
private static void initDefaultConfig() {
Configurator configurator = new Configurator();
Method[] methods = configurator.getClass().getMethods();
for (Method method : methods) {
DefaultConfiguration annos = method.getAnnotation(DefaultConfiguration.class);
if (annos != null) {
try {
method.invoke(configurator);
break;
} catch (Exception e) {
ExceptionHandler.handleException(e, AppConfig.class);
}
}
}
}
protected static void loadProperties(String fileName) {
(...)
}
}
The only pitfall you face: If you have more than one static code block, the execution order is the same as the order in the code.