A class with the @Bean
or @Component
will be loaded by spring on startup through the bean visitor mechanism. To exclude this bean from the Spring context at startup you can create a BeanPostProcessor
(here) and check for dedicated annotation BUT as far as I understand, you cannot put the bean back to the context at runtime.
As a consequence, you must make this bean 'intelligent' to perform the correct operation/mock (or send 503 HTTP code) when requests come in.
FF4j can indeed help you implementing this behaviour but not with a single annotation on top of your REST Controller. What you could do :
- Create an interface, annotate the interface with the dedicated FF4J annotation
- Create 2 implementations of the interface, each time with a different name
- Use FF4J to choose an implementation or another at runtime.
Here some code snippet to get the idea :
public interface GreetingService {
@Flip(name = "theFeatureIDToToggle", alterBean = "greeting.french")
String sayHello(String name);
}
@Component("greeting.french")
public class GreetingServiceFrenchImpl implements GreetingService {
public String sayHello(String name) {return "Bonjour " + name;
}
@Component("greeting.english")
public class GreetingServiceEnglishImpl implements GreetingService {
public String sayHello(String name) {return "Hello " + name;
}
//... import
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-ff4j-aop-test.xml")
public class FeatureAdvisorTest {
@Autowired
private FF4j ff4j;
@Autowired
@Qualifier("greeting.english")
private GreetingService greeting
@Test
public void testAnnotatedFlipping_with_alterBean() {
ff4j.disable("theFeatureIDToToggle");
Assert.assertTrue(greeting.sayHello("CLU").startsWith("Hello"));
ff4j.enable("theFeatureIDToToggle");
Assert.assertTrue(greeting.sayHello("CLU").startsWith("Bonjour"));
}
}
You can toggle a single method or the whole class, as you wish all samples are available here.