spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.55k stars 38.12k forks source link

Undefined behaviour for annotation based configs when method return type doesn't match returned object [SPR-13287] #17877

Closed spring-projects-issues closed 5 years ago

spring-projects-issues commented 9 years ago

Nicholas Wertzberger opened SPR-13287 and commented

public class A implements B, C {

}

@Configuration
public class Configuration {
    @Bean
    public B getB() {
        return new A();
    }

    @Bean
    public D getD(B b) {
        return new D(b);
    }

    @Bean
    public E getE(C c) {
        return new E(c);
    }
}

If D is created first, E will also be successfully created (the object returned by getB implements C). If D is created second, E will fail to be created. The expected behavior is that getE should never succeed.


Affects: 4.1.1

spring-projects-issues commented 9 years ago

Juergen Hoeller commented

This is expected behavior since Spring always uses the most specific known type for any given bean. The initialization order may affect this quite signifantly, as you experienced in your scenario.

From another perspective, the return type of a factory method cannot be used to reliably narrow the visible type of a bean. It can only serve to narrow the pre-instantiation type hint, but after creation of a bean, the container will always use the bean's concrete type for matching purposes.

Juergen

spring-projects-issues commented 9 years ago

Nicholas Wertzberger commented

Hey, I think I should do a better job of explaining why this really is the wrong call with the story of how this was found - by allowing this undefined behavior, you are making products built on top of spring less stable.

You are breaking the principle of least surprise.

I received a product developed by another group and was asked to install it. It blew up claiming it couldn't satisfy the dependency. I told them about the issue, and I was informed it worked on all their desktops and their development server. I then spent two days tracking down every possible reason why environment configurations maybe different, to no avail.

Upon looking at the source code, we supposed that this could be a reasonable cause, and it was.

spring-projects-issues commented 9 years ago

Nicholas Wertzberger commented

I have updated this ticket with my plea for some level of understanding with what the ramifications of calling this "good enough" means. Whatever your choice here is, I won't fight anymore, but please make sure you understand what this means for your (still relatively pleased in spite of the loss of two days of my life - it really is a great framework) users.

spring-projects-issues commented 5 years ago

Bulk closing outdated, unresolved issues. Please, reopen if still relevant.