Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
feature flags made easy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="properties">
<map>
<entry key="imaginaryFeature.implementation.bean" value="oldImaginaryFeature"/>
</map>
</property>
</bean>
<bean id="application" class="com.eranharel.SpringPolymorphicApplication">
<constructor-arg ref="imaginaryFeature"/>
</bean>
<alias name="${imaginaryFeature.implementation.bean}" alias="imaginaryFeature"/>
<bean id="newImaginaryFeature" class="com.eranharel.NewImaginaryFeature" lazy-init="true"/>
<bean id="oldImaginaryFeature" class="com.eranharel.OldImaginaryFeature" lazy-init="true"/>
</beans>
public void runApplication() {
// ...
if (useNewImplementation) {
executeNewImaginaryFeatureImplementation();
} else {
executeOldImaginaryFeatureImplementation();
}
// ...
}
public interface ImaginaryFeature {
public void executeFeature();
}
class OldImaginaryFeature implements ImaginaryFeature {
@Override
public void executeFeature() {
System.out.println("old feature implementation");
}
}
class NewImaginaryFeature implements ImaginaryFeature {
@Override
public void executeFeature() {
System.out.println("new feature implementation");
}
}
public class PolymorphicApplication {
private final ImaginaryFeature imaginaryFeature;
public PolymorphicApplication() {
this.imaginaryFeature = createImaginaryFeature();
}
private ImaginaryFeature createImaginaryFeature() {
final String featureClass = System.getProperty("PolymorphicApplication.imaginaryFeature.class");
try {
return (ImaginaryFeature) Class.forName(featureClass).newInstance();
} catch (final Exception e) {
throw new IllegalStateException("Failed to create ImaginaryFeature of class " + featureClass, e);
}
}
public void runApplication() {
// ...
imaginaryFeature.executeFeature();
// ...
}
}
public class SpringPolymorphicApplication {
private final ImaginaryFeature imaginaryFeature;
public SpringPolymorphicApplication(final ImaginaryFeature imaginaryFeature) {
this.imaginaryFeature = imaginaryFeature;
}
public void runApplication() {
// ...
imaginaryFeature.executeFeature();
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.