本文主要是介绍@Configuration中proxyBeanMethods属性详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
proxyBeanMethods属性
基本说明
1.默认为true,调用@Bean标注的方法,会从spring容器取出bean,并不会重新创建bean;
2.当设置为false时,调用@Bean标注的方法时,会直接执行方法,即创建了新的对象,但该方法不会 被代理拦截,即不会走bean生命周期的一些行为,比如@PostConstruct注解标注函数;
具体的代码如下:
package org.example.kata.springboot;import jakarta.annotation.PostConstruct;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@SpringBootTest
public class ConfigurationTest {public static class MyBean2 {private MyBean1 myBean1;public MyBean2(MyBean1 myBean1) {this.myBean1 = myBean1;}@PostConstructpublic void init(){System.out.println("MyBean2初始化了");}}public static class MyBean1 {@PostConstructpublic void init(){System.out.println("MyBean1初始化了");}}// proxyBeanMethods 属性默认值是 true, 也就是说该配置类会被代理(CGLIB),在同一个配置文件中调用其它被 @Bean 注解标注的方法获取对象时会直接从 IOC 容器之中获取;@Configuration(proxyBeanMethods = true)public static class MyConfiguration1 {@Bean("myBean1True")public MyBean1 myBean1() {return new MyBean1();}@Bean("myBean2True")public MyBean2 myBean2() {// myBean1会从spring容器中取return new MyBean2(myBean1());}}@Configuration(proxyBeanMethods = false)public static class MyConfiguration2 {@Bean("myBean1False")public MyBean1 myBean1() {return new MyBean1();}@Bean("myBean2False")public MyBean2 myBean2() {// 会有warning,可以使用构造器注入的方式// myBean1()则单纯执行方法,不会被CGLib代理,不会走bean生命周期的一些行为,比如MyBean1的@PostConstruct注解函数不会走return new MyBean2(myBean1());}
// @Bean
// public MyBean2 myBean2(MyBean1 myBean1) {
// return new MyBean2(myBean1);
// }}@Autowiredprivate MyBean1 myBean1True;@Autowiredprivate MyBean2 myBean2True;@Autowiredprivate MyBean1 myBean1False;@Autowiredprivate MyBean2 myBean2False;@Testpublic void test() {System.out.println("test");}
}
其他说明
这篇关于@Configuration中proxyBeanMethods属性详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!