This example shows that classes annotated with @Component can register new beans using @Bean annotation on their methods, but such methods will not be CGLIB enhance proxies.
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;
@Configuration
@ComponentScan(basePackageClasses = ScanFactoryComponentExample.class, useDefaultFilters = false,
includeFilters = {@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
value = ScanFactoryComponentExample.TestBean.class)})
public class ScanFactoryComponentExample {
public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
ScanFactoryComponentExample.class);
MyBean bean = context.getBean(MyBean.class);
System.out.println(bean);
//accessing multiple times
bean = context.getBean(MyBean.class);
System.out.println(bean);
/*this will return a new instance because @Component methods are not
* CGLIB proxied*/
TestBean testBean = context.getBean(TestBean.class);
System.out.println(testBean.myBean());
}
@Component
static class TestBean {
@Bean
public MyBean myBean () {
return new MyBean();
}
}
}
Output
com.logicbig.example.MyBean@1c95649a
com.logicbig.example.MyBean@1c95649a
com.logicbig.example.MyBean@373137a0
Original PostThis example shows that classes annotated with @Configuration will be scanned as well, if they are in scan path.
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan(basePackageClasses = ScanConfigurationExample.class, useDefaultFilters = false,
includeFilters = {@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
value = ScanConfigurationExample.TestBean.class)})
public class ScanConfigurationExample {
public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
ScanConfigurationExample.class);
MyBean bean = context.getBean(MyBean.class);
System.out.println(bean);
//accessing multiple times
bean = context.getBean(MyBean.class);
System.out.println(bean);
/*this will return same instance because @Configuration classes even in scan path will be
* CGLIB proxied*/
TestBean testBean = context.getBean(TestBean.class);
System.out.println(testBean.myBean());
}
@Configuration
static class TestBean {
@Bean
public MyBean myBean () {
return new MyBean();
}
}
}
Output
com.logicbig.example.MyBean@28e5716a
com.logicbig.example.MyBean@28e5716a
com.logicbig.example.MyBean@28e5716a
Original Post