Spring generic bean definition singleton per generic type

Viewed 535

Is it possible to define a generic bean once like this:

@Configuration
public class TestConfiguration {

    @Bean
    public <T> EmitterProcessor<T> emitterProcessor() {
        return EmitterProcessor.create();
    }
}

and then have a unique instance per parameterized type T so that the following test passes:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
public class GenericBeanTest {

    @Autowired
    private EmitterProcessor<String> stringEmitterProcessor;

    @Autowired
    private EmitterProcessor<Integer> integerEmitterProcessor;

    @Test
    public void testExistsAndIsUnique() {
        assertNotNull(stringEmitterProcessor);
        assertNotNull(integerEmitterProcessor);
        assertNotSame(stringEmitterProcessor, integerEmitterProcessor);
    }
}

Currently the stringEmitterProcessor and integerEmitterProcessor are the same object so that the last line in the test assertNotSame(stringEmitterProcessor, integerEmitterProcessor); fails.

The only other way that I could imagine requires me to implement a custom BeanFactory that would make a distinction based on the parameterized type when autowiring by type.

0 Answers
Related