[Spring] ApplicationContext trong Spring Framework

by CuongNM49
2K views

Trong bài viết này chúng ta sẽ tìm hiểu chi tiết về ApplicationContext interface.

ApplicationContext?

Ta hãy cùng nhớ lại 2 khái niệm DI(Dependency Injection) và IoC(Inversion of Control) gây thương nhớ cho những developer của Spring framework. IoC Container chính là lõi của Spring Framework. IoC Container có chức năng tạo ra các đối tượng, liên kết chúng lại với nhau, cấu hình chúng, và quản lí vòng đời của chúng từ khi tạo ra đến khi bị hủy. IoC container sẽ sử dụng DI để quản lí các thành phần tạo nên một ứng dụng.

Trong Spring framwork IoC được mô tả qua BeanFactory và ApplicationContext interface. BeanFactory là root interface truy cập vào Spring IoC, cung cấp chức năng cơ bản để quản lí Bean. Còn ApplicationContext là sub-interface cúa BeanFactory interface. Do đó, nó cung cấp tất cả các chức năng cơ bản của BeanFactory cùng nhưng chức năng tiên tiến hơn cho các ứng dụng Spring và phù hợp hơn cho những ứng dụng J2EE.

Spring Bean

Trước khi đi chi tiết hơn về ApplicationContext interface ta cần xem qua khái niệm về Spring Bean.

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.

Hay hiểu đơn giản với các ứng dụng Spring, Bean là object được tạo ra và quản lí bới Spring IoC container.

Cấu hình Bean trong Container

Để ApplicationContext có thể quản lí được các Bean, ứng dụng phải cũng cấp cấu hình bean cho ApplicationContext container. Ta sẽ có những cách khác nhau cấu hình để cấu hình bean:

  1. XML-Based Configuration
  2. Java-Based Configuration
  3. Annotation-Based Configuration

XML-Based Configuration

Cuối cùng với cách cấu hình dựa trên XML, ta sẽ khai báo tất cả các cấu hình của Bean trong một file XML.

Ta sẽ khai báo Bean cho class UserConfiguration trong một file user-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<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="userService" class="com.cuongnm.applicationcontext.UserService">
    <constructor-arg name="userRepository" ref="userRepository" />
  </bean>
  
  <bean id="userRepository" class="com.cuongnm.applicationcontext.UserRepository" />
</beans>

Java-Based Configuration

Cấu hình dựa trên Java bằng cách sử dụng @Bean annotation bên trong 1 lớp @Configuration. Với mỗi @Bean annotation được khai báo đánh dấu cho một method để tạo ra 1 Spring Bean. Và những phương thức này đc chứa trong 1 class được đánh dấu là @Configuration – một class chứa các cấu hình Spring bean.

Ví dụ:

@Configuration
public class UserConfig {

  @Bean
  public UserService userService() {
    return new AccountService(userRepository());
  }

  @Bean
  public UserRepository userRepository() {
    return new UserRepository();
  }
}

Bằng cách đưa ra @Configuration ta sẽ xử lí class UserConfig như thẻ bean trong XML

Annotation-Based Configuration

Để sử dụng được phương pháp này, đầu tiên ta sẽ cấu hình trong XML để cho phép sử dụng Annotation-Based Configuration trong ứng dụng.

<context:annotation-config/>
<context:component-scan base-package="com.cuongnm.applicationcontext"/>

Thẻ context:annotation-config để khai báo cho việc sử dụng annotation-based mappings và thẻ context:component-scan với tham số base-package cho Spring tìm được package chưa các annotated classes.

Sau đó, ta sẽ sử dụng các annotation được cung cấp bởi Spring để đánh dấu cho các class, method, constructor, field trong Java để cấu hình cho Bean như @Component, @Controller, @Service, @Repository, @Autowired.

Ví dụ với class UserService được khai báo là một Bean sử dụng @Component annotation:

@Component
public class UserService {
  
}

Ta có thể lấy ra Bean này bằng cách:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext/user-bean-config.xml");
UserService userService = context.getBean(UserService.class);
assertNotNull(userService);

Cách sử dụng ApplicationContext

Cũng như việc cấu hình cho Bean thì cũng có rất nhiều cách sử dụng ApplicationContext interface.

1) ClassPathXmlApplicationContext

Phương pháp này sẽ tải các Bean config từ các file XML nằm trong đường dẫn classpath.

ApplicationContext context = new ClassPathXmlApplicationContext ("user-bean-config.xml");

2) FileSystemXmlApplicationContext

Sử dụng các Bean config từ các file XML trong FileSystem hay từ URL.

ApplicationContext context = new FileSystemXmlApplicationContext (“c: /myconfig.xml”);

3) AnnotationConfigApplicationContext

AnnotationConfigApplicationContext được sử dụng với Java-Based Configuration cho các cấu hình Bean.

Ví dụ:

public static void main(String[]args){
<em>/* Creating Spring IoC Container Without XML configuration file*/</em>
ApplicationContext context= new AnnotationConfigApplicationContext(UserConfig.class);
MyBean beanObj = context.getBean(UserService.class);
}

Với ví dụ này ApplicationContext được lấy từ UserConfig class. Chúng ta lấy các cấu hình Bean từ một class được chú thích @Configuratation và nó sẽ được khai báo:

@Configuration
public class UserConfig {

  @Bean
  public UserService userService() {
    return new AccountService(userRepository());
  }

  @Bean
  public UserRepository userRepository() {
    return new UserRepository();
  }
}

3) XmlWebApplicationContext và AnnotationConfigWebApplicationContext

XmlWebApplicationContext được sử dụng để đại diện cho Spring container trong ứng dụng Web. Và nó tải các cấu hình bean từ những file XML với mặc định từ đường dẫn “/WEB-INF/applicationContext.xml”. Chúng ta cũng có thể chỉ định được dẫn của nó qua tham số contextConfigLocation của ContextLoaderListener hoặc DispatcherServlet trong web.xml.

Giống như XmlWebApplicationContext là class tương ứng với ClassPathXmlApplicationContext và FileSystemXmlApplicationContext và được sử dụng để tạo ra ApplicationContext cho các ứng dụng web, tương tự, AnnotationConfigWebApplicationContext là class tương ứng với AnnotationConfigApplicationContext.

Lời kết

Tóm tắt lại những gì mình muốn nói ở bài viết này, mục đích giúp chúng ta hiểu về ApplicationContext trong Spring, hiểu cách sử dụng, triển khai ApplicationContext. Cũng như cách gọi Spring container bằng ApplicationContext mang đến nhiều chức năng hơn so với BeanFactory.

Bài viết được tham khảo từ “https://www.baeldung.com/spring-application-context“.

Cảm ơn các bạn đã đọc bài viết!

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

You may also like