美文网首页
springboot @bean使用

springboot @bean使用

作者: zhengaoly | 来源:发表于2021-11-26 11:37 被阅读0次

    方式一

    一般在@configration类中定义一个函数,通过@bean注解,可以创建bean
    如下:

    public class BeanA {
        public BeanA() {
            System.out.println("beanA ");
        }
    }
    
    @Configuration
    public class WebConfig {
        public WebConfig() {
            System.out.println("webconfig");
        }
    
        @Autowired
        BeanA beanA;
        @Bean
        public BeanA beanA(){
            BeanA beanA = new BeanA();
            System.out.println("beanA创建"+System.currentTimeMillis()+":"+beanA.hashCode());
            return beanA;
        }
        public void hello(){
            System.out.println(beanA.hashCode());
        }
    }
    
    

    输出:

    webconfig
    beanA 
    beanA创建1637895808196:273295484
    

    可知,先创建了webconfig,然后创建beanA,最后在对webconfig注入beanA

    方式二

    如下:

    public class BeanA {
        public BeanA() {
            System.out.println("beanA ");
        }
    }
    
    @Configuration
    public class WebConfig {
        public WebConfig() {
            System.out.println("webconfig");
        }
        @Bean
        public BeanA beanA(){
            BeanA beanA = new BeanA();
            System.out.println("beanA创建"+System.currentTimeMillis()+":"+beanA.hashCode());
            return beanA;
        }
        public void hello(){
            System.out.println(beanA().hashCode());
        }
    }
    
    

    此处hello函数,调用时,调用beanA的方式为beanA(),类似于函数的调用,但是实际上不会重新创建beanA,而是取的beanA对象,经验证,是同一个对象

    可以理解为beanA()被@Bean注解以后,就不是一个单纯的函数,而是一个bean对象。对beanA()的调用,实际上是取bean对象。
    其本质是方法被spring容器代理了。
    如下:

    springboot注解@Configuration属性proxyBeanMethods:

    proxyBeanMethods属性默认值是true,也就是说该配置类会被代理(CGLIB),在同一个配置文件中调用其它被@Bean注解标注的方法获取对象时会直接从IOC容器之中获取;注解的意思是proxyBeanMethods配置类是用来指定@Bean注解标注的方法是否使用代理,默认是true使用代理,直接从IOC容器之中取得对象;如果设置为false,也就是不使用注解,每次调用@Bean标注的方法获取到的对象和IOC容器中的都不一样,是一个新的对象,所以我们可以将此属性设置为false来提高性能;

    bean依赖关系,可以通过函数参数体现

    image.png

    相关文章

      网友评论

          本文标题:springboot @bean使用

          本文链接:https://www.haomeiwen.com/subject/aywtxrtx.html