@lazy注入

该文章展示了一个使用SpringBoot和ApacheDubbo的示例提供者应用,其中`DemoService`被两次@Autowired,一次不带@Lazy,一次带有@Lazy。@Lazy注解使得依赖在实际使用时才会初始化,而不是在应用启动时。文章通过代码示例解释了@Lazy注解的工作原理和效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*

  • Licensed to the Apache Software Foundation (ASF) under one or more
  • contributor license agreements. See the NOTICE file distributed with
  • this work for additional information regarding copyright ownership.
  • The ASF licenses this file to You under the Apache License, Version 2.0
  • (the “License”); you may not use this file except in compliance with
  • the License. You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
    
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an “AS IS” BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.
    */

package org.apache.dubbo.springboot.demo.provider;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.springboot.demo.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Lazy;

@SpringBootApplication
@EnableDubbo
public class ProviderApplication implements ApplicationRunner {

@Autowired
private DemoService demoService1;


@Lazy
@Autowired
private DemoService demoService2;
public static void main(String[] args) {
    SpringApplication.run(ProviderApplication.class, args);
}

@Override
public void run(final ApplicationArguments args) throws Exception {
    System.out.println("(demoService1 == demoService2) = " + (demoService1 == demoService2));
    //false
    //原因: lazy注入是注入的一个lazy代理, 代理中的target指向spring getBean, 从而实现了在调用属性的方法时才获取bean
    // 源码: lazyLookup ?  buildLazyResourceProxy ()
    // ps0: lazy注入不是不注入, 是不注入不就空指针了吗
    // ps1: 是加了一个代理, 没有什么是加一层代理解决不了的, 比如 @RefreshScope 热更新, @lazy注入依赖
    // ps2: 这里的lazy是用在 autowired依赖注入, 当用在@compont上时,bean肯定是同一个, 不用加一层, 看上去也会懒生成(最终要看源码的意思)
    // ps3: api getbean肯定还是同一个
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值