micronaut-projects / micronaut-core

Micronaut Application Framework
http://micronaut.io
Apache License 2.0
6.07k stars 1.07k forks source link

IoC fails to inject object implementing Collection<E> #3773

Closed ratcashdev closed 3 years ago

ratcashdev commented 4 years ago

Steps to Reproduce

consider the following test snippet:

import io.micronaut.context.ApplicationContext;
import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Singleton;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;

public class GenericInjectionTest {

    public static class MyContainer<T> extends AbstractCollection<T>{
        List<T> data;

        public MyContainer() {
            this.data = new ArrayList<>();
        }

        @Override
        public Iterator<T> iterator() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public int size() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }

    @Factory
    public static class MyFactory {
        @Bean
        public MyContainer<String> constructContainer() {
            return new MyContainer<>();
        }
    }

    @Singleton
    public static class ContainerUser {
        @Inject
        MyContainer list1;

        @Inject
        MyContainer<String> list2;

    }

    @Test
    public void testInjection() {
        try (ApplicationContext ctx = ApplicationContext.run()) {
            Optional<ContainerUser> bean = ctx.findBean(ContainerUser.class);
            assertNotNull(bean.get().list1);
           // fails here
            assertNotNull(bean.get().list2);
        };
    }

}

Expected Behaviour

Test should be successful.

Actual Behaviour

bean.get().list2 is null. It will not be null if the MyContainer would not implement AbstractCollection or Collection<E> for that matter.

Environment Information

ratcashdev commented 4 years ago

Initial related discussion: https://gitter.im/micronautfw/questions?at=5f1934b321f5e643aa43e442

graemerocher commented 3 years ago

bean collections are supported in 3.0