Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spring Bean Injection

Given this question on Stackoverflow I wanted to check whether there is a difference between this style of Bean definition (variant 1):

@Configuration
public class BeanConfiguration {

    @Bean
    public FirstClass firstClass() {
        return new FirstClass();
    }

    @Bean
    public SecondClass secondClass() {
        return new SecondClass(firstClass());
    }

    public static class FirstClass {

        public String get() {
            return "FirstClass";
        }

    }

    public class SecondClass {

        private final FirstClass firstClass;

        public SecondClass(FirstClass firstClass) {
            this.firstClass = firstClass;
        }

        public String get() {
            return firstClass.get();
        }

    }

}

and this style (variant 2):

@Configuration
public class BeanConfiguration {

    @Bean
    public FirstClass firstClass() {
        return new FirstClass();
    }

    @Bean
    public SecondClass secondClass(FirstClass firstClass) {
        return new SecondClass(firstClass);
    }

    public static class FirstClass {

        public String get() {
            return "FirstClass";
        }

    }

    public class SecondClass {

        private final FirstClass firstClass;

        public SecondClass(FirstClass firstClass) {
            this.firstClass = firstClass;
        }

        public String get() {
            return firstClass.get();
        }

    }

}

Given the documentation for mocking beans in the Spring Docs one could assume that mocking does not properly work with variant 1, but the following test works with both variants:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = BeanConfiguration.class)
public class BeanInjectionTest {

    @MockBean
    private BeanConfiguration.FirstClass firstClass;

    @Autowired
    private BeanConfiguration.SecondClass secondClass;

    @Test
    public void testInjectionWithMockedDependency() {
        given(this.firstClass.get()).willReturn("mock");
        assertThat(secondClass.get(), is("mock"));
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.