Skip to content

Instantly share code, notes, and snippets.

@michaellihs
Created September 29, 2016 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaellihs/700cb3bfd961e1566682040fce6d4e98 to your computer and use it in GitHub Desktop.
Save michaellihs/700cb3bfd961e1566682040fce6d4e98 to your computer and use it in GitHub Desktop.
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