Skip to content

Conflicting Conditional bean behavior  #24156

Closed
@JigarJoshi

Description

@JigarJoshi
package com.example.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;

@SpringBootApplication
public class SpringBootDemoApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(SpringBootDemoApplication.class, args);
        System.out.println("Bean found ? " + (ctx.getBean(Foo.class) != null));
    }
}

@Configuration
class TestConfiguration {

    @Bean
    @Conditional(AlwaysMismatch.class)
    public Foo foo(int dummy) {
        return new Foo();
    }

    @Bean
    @Conditional(AlwaysMatch.class)
    public Foo foo() {
        return new Foo();
    }

}

class AlwaysMatch implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        return true;
    }
}

class AlwaysMismatch implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        return false;
    }
}


class Foo {
}

Expectation

With above code I expect one bean of type com.example.springbootdemo.Foo contributed with bean-name foo.

Actual behavior
No bean of type com.example.springbootdemo.Foo is registered.

With a slight change in above code.

From

@Configuration
class TestConfiguration {

    @Bean
    @Conditional(AlwaysMismatch.class)
    public Foo foo(int dummy) {
        return new Foo();
    }

    @Bean
    @Conditional(AlwaysMatch.class)
    public Foo foo() {
        return new Foo();
    }
}

to

@Configuration
class TestConfiguration {

    @Bean
    @Conditional(AlwaysMismatch.class)
    public Foo foo(int dummy) {
        return new Foo();
    }

    @Bean
    @Conditional(AlwaysMatch.class)
    public Foo foo1() {
        return new Foo();
    }
}

bean of type com.example.springbootdemo.Foo is registered.

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: duplicateA duplicate of another issue

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions