Featured image of post Java 中 Bean、单例及单例 Bean 的学习笔记

Java 中 Bean、单例及单例 Bean 的学习笔记

912字

Java 中 Bean、单例及单例 Bean 的学习笔记

一、Bean

(一)概念

在 Java 开发,尤其是 Spring 框架中,Bean 是被 Spring 容器实例化、配置与管理的对象。Spring 容器掌控 Bean 的创建、生命周期管理以及依赖关系处理。

(二)示例 - 图书管理系统中的 BookService

  1. BookService 类定义
1
2
3
4
5
6
7
8
9
public class BookService {
    public void addBook(String title, String author) {
        System.out.println("Adding book: " + title + " by " + author);
    }

    public void findBook(String title) {
        System.out.println("Finding book: " + title);
    }
}

此 BookService 类负责处理图书相关业务逻辑,如添加和查询图书。

  1. 使用 Spring 注解配置为 Bean
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import org.springframework.stereotype.Service;

@Service
public class BookService {
    public void addBook(String title, String author) {
        System.out.println("Adding book: " + title + " by " + author);
    }

    public void findBook(String title) {
        System.out.println("Finding book: " + title);
    }
}

通过 @Service 注解,将 BookService 声明为 Spring 中的一个 Bean。

  1. 在 BookController 中依赖注入使用
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BookController {

    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/addBook")
    public String addBook(@RequestParam String title, @RequestParam String author) {
        bookService.addBook(title, author);
        return "Book added successfully";
    }
}

BookController 通过依赖注入获取 BookService 的实例,进而调用其方法处理业务。

二、单例模式

(一)概念

单例是一种设计模式,确保一个类在整个应用程序中仅有一个实例,并提供全局访问点获取该实例。

(二)示例 - 日志记录器

  1. 饿汉式单例模式实现日志记录器
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class LoggerSingleton {
    private static final LoggerSingleton INSTANCE = new LoggerSingleton();
    private LoggerSingleton() {}

    public void logMessage(String message) {
        System.out.println("Logging: " + message);
    }

    public static LoggerSingleton getInstance() {
        return INSTANCE;
    }
}

类加载时就创建 INSTANCE 实例,构造函数私有防止外部实例化,通过 getInstance 方法获取唯一实例。

  1. 使用示例
1
2
3
4
5
6
7
8
9
public class MainApp {
    public static void main(String[] args) {
        LoggerSingleton logger1 = LoggerSingleton.getInstance();
        LoggerSingleton logger2 = LoggerSingleton.getInstance();
        logger1.logMessage("First log message");
        logger2.logMessage("Second log message");
        System.out.println(logger1 == logger2); // 输出 true,表明是同一个实例
    }
}

多次获取的 LoggerSingleton 实例是同一个,保证日志记录的一致性并避免资源浪费。

三、单例 Bean

(一)概念

在 Spring 框架中,默认情况下,Spring 容器创建的 Bean 是单例 Bean,即在整个 Spring 应用上下文中,特定 Bean 定义仅有一个实例。

(二)示例 - BookService 作为单例 Bean

  1. UserService 和 OrderService 依赖 BookService
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    private final BookService bookService;

    @Autowired
    public UserService(BookService bookService) {
        this.bookService = bookService;
    }

    public void userRelatedBookOperation() {
        bookService.addBook("User - Book 1", "User - Author 1");
    }
}

@Service
public class OrderService {
    private final BookService bookService;

    @Autowired
    public OrderService(BookService bookService) {
        this.bookService = bookService;
    }

    public void orderRelatedBookOperation() {
        bookService.findBook("Order - Book 1");
    }
}

UserService 和 OrderService 都依赖 BookService,且注入的是同一个 BookService 实例。

  1. 共享状态特性
    若 UserService 修改了 BookService 的内部状态,OrderService 获取到的 BookService 也会体现该修改,因为它们共享同一实例。这展示了 Spring 中单例 Bean 的特性,有助于减少内存开销并方便组件间共享状态与行为。
如对内容有异议,请联系关邮箱2285786274@qq.com修改