Skip to main content

Command Palette

Search for a command to run...

Bài 3: Bean và Bean Scope

Published
4 min readView as Markdown

1. Định nghĩa Bean trong Spring

Bean là một đối tượng được quản lý bởi Spring IoC container. Mỗi bean trong Spring là một thành phần hoặc một đối tượng có thể được tạo, quản lý, và hủy bỏ bởi IoC container. Beans được định nghĩa trong file cấu hình Spring hoặc bằng cách sử dụng các annotation.

2. Các loại Bean Scope

Bean Scope xác định phạm vi tồn tại của một bean trong IoC container. Spring hỗ trợ nhiều loại scope cho beans, trong đó phổ biến nhất là:

  • Singleton: (Mặc định) Mỗi container chỉ tạo một instance duy nhất của bean.

  • Prototype: Mỗi lần yêu cầu một bean, container sẽ tạo một instance mới.

  • Request: Mỗi HTTP request tạo một instance mới. (chỉ dùng cho web applications)

  • Session: Mỗi HTTP session tạo một instance mới. (chỉ dùng cho web applications)

  • Global Session: Dùng cho các ứng dụng portlet, mỗi global HTTP session tạo một instance mới. (chỉ dùng cho web applications)

3. Cách tạo và quản lý Bean

3.1. Cấu hình Bean bằng XML

Trong file cấu hình XML, chúng ta có thể định nghĩa beans và chỉ định scope của chúng.

Ví dụ về Singleton Scope:

<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloWorld" class="com.example.HelloWorld" scope="singleton">
        <property name="message" value="Hello Spring!"/>
    </bean>

</beans>

Ví dụ về Prototype Scope:

<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloWorld" class="com.example.HelloWorld" scope="prototype">
        <property name="message" value="Hello Spring!"/>
    </bean>

</beans>

3.2. Cấu hình Bean bằng Java Annotations

Chúng ta có thể sử dụng các annotation để định nghĩa beans và chỉ định scope của chúng. Các annotation phổ biến bao gồm @Component, @Service, @Repository, và @Controller.

Ví dụ về Singleton Scope (Mặc định):

// HelloWorld.java
@Component
public class HelloWorld {
    private String message;

    @Value("Hello Spring!")
    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("Your Message: " + message);
    }
}

// MainApp.java
@SpringBootApplication
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(MainApp.class, args);
        HelloWorld helloWorld1 = context.getBean(HelloWorld.class);
        HelloWorld helloWorld2 = context.getBean(HelloWorld.class);

        System.out.println(helloWorld1 == helloWorld2); // true
    }
}

Ví dụ về Prototype Scope:

// HelloWorld.java
@Component
@Scope("prototype")
public class HelloWorld {
    private String message;

    @Value("Hello Spring!")
    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("Your Message: " + message);
    }
}

// MainApp.java
@SpringBootApplication
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(MainApp.class, args);
        HelloWorld helloWorld1 = context.getBean(HelloWorld.class);
        HelloWorld helloWorld2 = context.getBean(HelloWorld.class);

        System.out.println(helloWorld1 == helloWorld2); // false
    }
}

4. Tạo và quản lý Beans

4.1. Sử dụng AnnotationConfigApplicationContext

AnnotationConfigApplicationContext là một implementation của ApplicationContext, dùng để khởi tạo và quản lý beans được cấu hình bằng Java Annotations.

// AppConfig.java
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}

// HelloWorld.java
@Component
@Scope("singleton")
public class HelloWorld {
    private String message;

    @Value("Hello Spring!")
    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("Your Message: " + message);
    }
}

// MainApp.java
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        HelloWorld helloWorld = context.getBean(HelloWorld.class);
        helloWorld.getMessage();
    }
}

4.2. Sử dụng ClassPathXmlApplicationContext

ClassPathXmlApplicationContext là một implementation của ApplicationContext, dùng để khởi tạo và quản lý beans được cấu hình bằng XML.

// HelloWorld.java
public class HelloWorld {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("Your Message: " + message);
    }
}

// MainApp.java
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
        helloWorld.getMessage();
    }
}

5. Kết luận

Trong bài viết này, chúng ta đã tìm hiểu về Bean và Bean Scope trong Spring Framework. Chúng ta đã thấy cách định nghĩa và quản lý các bean bằng XML và Java Annotations, cũng như các loại scope khác nhau để kiểm soát vòng đời của các bean. Những kiến thức này giúp chúng ta hiểu rõ hơn về cách Spring quản lý các đối tượng và cung cấp các phụ thuộc, giúp ứng dụng dễ bảo trì và mở rộng hơn.

Trong bài viết tiếp theo, chúng ta sẽ đi sâu vào Streams API trong Java 8, một công cụ mạnh mẽ để xử lý dữ liệu.

More from this blog

devngu

169 posts