proxyBeanMethods说明
根据注释proxyBeanMethods是为了让使用@Bean注解的方法被代理而实现bean的生命周期的行为。
1.设置为true,那么直接调用方法获取bean,不会创建新的bean,而是会走bean的生命周期的行为。
2.设置为false, 那么直接调用方法获取bean,会创建新的bean,且不会走bean的生命周期的行为。
Configuration 源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(annotation = Component.class)
String value() default "";
boolean proxyBeanMethods() default true;
}
测试验证代码
测试代码
public class AnnotationConfigApplicationContextTest {
@Test
public void refresh(){
AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
MyBean myBean=ctx.getBean(MyBean.class);
myBean.sayHello();
YourBean yourBean=ctx.getBean(YourBean.class);
yourBean.sayHello();
}
}
Configuration代码,设置为false
@Configuration(proxyBeanMethods = false)
public class AppConfig {
@Bean
public MyBean myBean(){
return new MyBean();
}
@Bean
public YourBean yourBean(){
return new YourBean(myBean());
}
}
Mybean代码
public class MyBean {
public MyBean(){
System.out.println("MyBean construct......");
}
@PostConstruct
public void init(){
System.out.println("MyBean PostConstruct ....");
}
public void sayHello(){
System.out.println("Hi MyBean ,hello world!");
}
}
YourBean代码
public class YourBean {
public MyBean myBean;
public YourBean(MyBean myBean){
System.out.println("YourBean construct...");
this.myBean=myBean;
}
@PostConstruct
public void init(){
System.out.println("YourBean PostConstruct...");
}
public void sayHello(){
System.out.println("Hi YourBean ,hello world!");
}
}
执行refresh测试测试代码结果(proxyBeanMethods = false)
MyBean construct......打印了两次,说明被new了两次
10:04:56.066 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBean'
MyBean construct......
MyBean PostConstruct ....
10:04:56.069 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'yourBean'
MyBean construct......
YourBean construct...
YourBean PostConstruct...
Hi MyBean ,hello world!
Hi YourBean ,hello world!
执行refresh测试测试代码结果(proxyBeanMethods = true)
MyBean construct......只打印了一次,说明只被new了一次。
10:06:51.727 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBean'
MyBean construct......
MyBean PostConstruct ....
10:06:51.741 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'yourBean'
YourBean construct...
YourBean PostConstruct...
Hi MyBean ,hello world!
Hi YourBean ,hello world!
网友评论