Skip to content

一、@Lazy 装配Bean实现的懒汉式使用

默认情况下,Spring 容器装配Bean使用的是饿汉式

  • 添加 @Lazy 注解在 UserServiceImpl.java 实现类中。
    • value 属性:默认为 true (开启懒加载), 可设置为 false (关闭懒加载)
  • 作用: 当 UserServiceImpl.java 类被创建和调用,才被初始注入到 Spring 容器中。
java
package org.example.spring5.service.impl;

import org.example.spring5.service.UserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:17 <br>
 * @since: 1.0 <br>
 * @description: UserService <br>
 */
@Service
@Lazy
public class UserServiceImpl implements UserService {

    public UserServiceImpl(){
        System.out.println("UserServiceImpl对象将被注入到容器中...");
    }
}
  • 启动调用 UserService, 实现懒汉式加载Bean对象
java
package org.example.spring5;

import org.example.spring5.config.SpringConfiguration;
import org.example.spring5.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:27 <br>
 * @since: 1.0 <br>
 * @description: SpringApplication <br>
 */
public class SpringApplication {

    private static AnnotationConfigApplicationContext annotationConfigApplicationContext;

    public static void main(String[] args) {
        annotationConfigApplicationContext  = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        System.out.println("Bean对象已装配完毕...");

        // @Service 的方式创建和调用对象
        UserService userServiceBean = annotationConfigApplicationContext.getBean(UserService.class);
        System.out.println(userServiceBean);
    }
}
  • 输出结果
log
Bean对象已装配完毕...
UserServiceImpl对象将被注入到容器中...
org.example.spring5.service.impl.UserServiceImpl@4efc180e