Let explain with an example:
Having this bean:
public class Foo {
private String name;
Foo(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
And this service:
public class FooService {
private Foo foo;
FooService(Foo foo) {
this.foo = foo;
}
Foo getFoo() {
return this.foo;
}
}
Given the following Spring configuration:
@Configuration
public class SpringContext {
// @Bean
// Foo foo() {
// return new Foo("foo");
// }
@Bean
@Autowired(required = false)
FooService fooService(Foo foo) {
if (foo == null) {
return new FooService(new Foo("foo"));
}
return new FooService(foo);
}
}
For completeness here is a simple unit test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringContext.class})
public class SpringAppTests {
@Autowired
private FooService fooService;
@Test
public void testGetName() {
Assert.assertEquals("foo", fooService.getFoo().getName());
}
}
Then loading the context will throw a NoSuchBeanDefinitionException (Foo).
Can anyone see anything wrong/missing on this example, or provide me a reason for that?
Thank you! Christian