@Bean inside class with @Configuration and without it
The difference is that with @Configuration
you can call one @Bean
method from another and get a fully initialized instance, as follows:
public class Foo {
@Value("Hello, world!")
public String value;
}
@Configuration
public class Config {
@Bean
public Foo createFoo() {
Foo foo = new Foo();
System.out.println(foo.value); // Prints null - foo not initialized yet
return foo;
}
@Bean
public Bar createBar() {
Foo foo = createFoo();
System.out.println(foo.value); // Prints Hello, world! - foo have been initialized by the interceptor
return new Bar(foo);
}
}
@Bean [instance method] inside @Component - One method with @Bean instance call other method @Bean instance , then it would be simple java semantics call i.e. Object won't returned by Spring container , It would be normal return from java instance factory method,because Component class don't extends CGLIB.
@Bean [instance method] inside @Configuration - In this case , spring container would be returning reference to exisiting object. It won't be normal java sematic call.
@Bean on static method inside Configuration & Component Class - In this case , @Bean method would never be intercepted by the container neither in Configuration class nor in Component Sterotype class.