1. Gambaran keseluruhan
Dalam tutorial ini, kita akan melihat antara muka Spring ApplicationConext secara terperinci.
2. Antaramuka ApplicationContext
Salah satu ciri utama rangka Spring adalah wadah IoC (Inversion of Control). Bekas Spring IoC bertanggungjawab menguruskan objek aplikasi. Ia menggunakan suntikan kebergantungan untuk mencapai pembalikan kawalan.
Antara muka BeanFactory dan ApplicationContext mewakili wadah Spring IoC . Di sini, BeanFactory adalah antara muka root untuk mengakses bekas Spring. Ia menyediakan fungsi asas untuk menguruskan kacang.
Sebaliknya, ApplicationContext adalah sub-antara muka BeanFactory . Oleh itu, ia menawarkan semua fungsi BeanFactory.
Tambahan pula, ia menyediakan lebih banyak fungsi khusus perusahaan . Ciri-ciri penting ApplicationContext adalah menyelesaikan mesej, menyokong pengantarabangsaan, menerbitkan acara, dan konteks aplikasi lapisan tertentu . Inilah sebabnya mengapa kami menggunakannya sebagai bekas Spring lalai.
3. Apa itu Kacang Musim Bunga?
Sebelum kita menyelami lebih dalam bekas ApplicationContext , penting untuk mengetahui mengenai kacang kacang. Pada musim bunga, kacang adalah objek yang dijadikan tempat, dipasang, dan dikendalikan oleh bekas Spring .
Oleh itu, perlukah kita mengkonfigurasi semua objek aplikasi kita sebagai biji kacang? Oleh itu, sebagai amalan terbaik, kita tidak seharusnya.
Seperti pada dokumentasi Spring, secara umum, kita harus menentukan kacang untuk objek lapisan perkhidmatan, objek akses data (DAO), objek persembahan, objek infrastruktur seperti Hibernate SessionFactories, JMS Queues, dan sebagainya.
Juga, biasanya, kita tidak boleh mengkonfigurasi objek domain yang halus di dalam bekas. Biasanya tanggungjawab DAO dan logik perniagaan untuk membuat dan memuatkan objek domain.
Oleh itu, mari kita tentukan kelas Java sederhana yang akan kita gunakan sebagai kacang kacang dalam tutorial ini:
public class AccountService { @Autowired private AccountRepository accountRepository; // getters and setters }
4. Mengkonfigurasi Kacang dalam Bekas
Seperti yang kita ketahui, tugas utama ApplicationContext adalah menguruskan kacang.
Jadi, aplikasi mesti menyediakan konfigurasi kacang ke bekas ApplicationContext . Oleh itu, konfigurasi kacang kacang terdiri daripada satu atau lebih definisi kacang. Juga, Spring menyokong pelbagai cara mengkonfigurasi kacang.
4.1. Konfigurasi Berasaskan Java
Pertama, kita akan mulakan dengan konfigurasi berasaskan Java kerana ini adalah kaedah konfigurasi kacang terbaru dan paling disukai. Ia tersedia dari Spring 3.0 dan seterusnya.
Konfigurasi Java biasanya menggunakan kaedah @ Bean- nototated dalam kelas @Configuration . The @Bean anotasi pada kaedah yang menunjukkan bahawa kaedah mencipta kacang Spring. Lebih-lebih lagi, kelas yang diberi penjelasan dengan @Configuration menunjukkan bahawa ia mengandungi konfigurasi kacang musim bunga.
Oleh itu, mari buat kelas konfigurasi untuk menentukan kelas AccountService kami sebagai Spring bean:
@Configuration public class AccountConfig { @Bean public AccountService accountService() { return new AccountService(accountRepository()); } @Bean public AccountRepository accountRepository() { return new AccountRepository(); } }
4.2. Konfigurasi Berasaskan Anotasi
Spring 2.5 memperkenalkan konfigurasi berasaskan anotasi sebagai langkah pertama untuk memungkinkan konfigurasi kacang di Java.
Dalam pendekatan ini, pertama-tama kami mengaktifkan konfigurasi berasaskan anotasi melalui konfigurasi XML. Kemudian, kami menggunakan sekumpulan anotasi pada kelas, kaedah, konstruktor, atau ladang Java kami untuk mengkonfigurasi kacang. Beberapa contoh anotasi ini ialah @Component , @Controller , @Service , @Repository , @Autowired , dan @Qualifier .
Terutama, kami juga menggunakan anotasi ini dengan konfigurasi berdasarkan Java. Selain itu, Spring terus menambahkan lebih banyak keupayaan pada anotasi ini dengan setiap siarannya.
Jadi, sekarang, mari kita lihat contoh ringkas konfigurasi ini.
Pertama, kami akan membuat konfigurasi XML, user-bean-config.xml , untuk mengaktifkan anotasi:
Di sini, yang anotasi-config tag membolehkan pemetaan berdasarkan penjelasan- . Selain itu, komponen-scan tag memberitahu Spring di mana untuk mencari kelas beranotasi.
Kedua, kami akan membuat kelas UserService dan mendefinisikannya sebagai Spring bean menggunakan anotasi @Component :
@Component public class UserService { // user service code }
Dan kemudian, kami akan menulis kes ujian mudah untuk menguji konfigurasi ini:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext/user-bean-config.xml"); UserService userService = context.getBean(UserService.class); assertNotNull(userService);
4.3. Konfigurasi Berasaskan XML
Akhirnya, mari kita lihat konfigurasi berasaskan XML. Ini adalah kaedah tradisional untuk mengkonfigurasi kacang pada musim bunga.
Jelas, dalam pendekatan ini, kami melakukan semua pemetaan kacang dalam fail konfigurasi XML .
Oleh itu, mari buat fail konfigurasi XML, account-bean-config.xml , dan tentukan kacang untuk kelas AccountService kami :
5. Jenis-jenis ApplicationContext
Spring menyediakan pelbagai jenis bekas ApplicationContext yang sesuai untuk keperluan yang berbeza. Ini adalah pelaksanaan antara muka ApplicationContext . Oleh itu, mari kita lihat beberapa jenis ApplicationContext yang biasa .
5.1. AnotasiConfigApplicationContext
First, let's see the AnnotationConfigApplicationContext class, which was introduced in Spring 3.0. It can take classes annotated with @Configuration, @Component, and JSR-330 metadata as input.
So, let's see a simple example of using the AnnotationConfigApplicationContext container with our Java-based configuration:
ApplicationContext context = new AnnotationConfigApplicationContext(AccountConfig.class); AccountService accountService = context.getBean(AccountService.class);
5.2. AnnotationConfigWebApplicationContext
AnnotationConfigWebApplicationContextis a web-based variant of AnnotationConfigApplicationContext.
We may use this class when we configure Spring's ContextLoaderListener servlet listener or a Spring MVC DispatcherServlet, in a web.xml file.
Moreover, from Spring 3.0 onward, we can also configure this application context container programmatically. All we need to do is to implement the WebApplicationInitializer interface:
public class MyWebApplicationInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(AccountConfig.class); context.setServletContext(container); // servlet configuration } }
5.3. XmlWebApplicationContext
If we use the XML based configuration in a web application, we can use the XmlWebApplicationContext class.
As a matter of fact, configuring this container is like the AnnotationConfigWebApplicationContext class only, which means we can configure it in web.xml or implement the WebApplicationInitializer interface:
public class MyXmlWebApplicationInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setConfigLocation("/WEB-INF/spring/applicationContext.xml"); context.setServletContext(container); // Servlet configuration } }
5.4. FileSystemXMLApplicationContext
We use the FileSystemXMLApplicationContext class to load an XML-based Spring configuration file from the file system or from URLs. This class is useful when we need to load the ApplicationContext programmatically. In general, test harnesses and standalone applications are some of the possible use cases for this.
For example, let's see how we can create this Spring container and load the beans for our XML-based configuration:
String path = "C:/myProject/src/main/resources/applicationcontext/account-bean-config.xml"; ApplicationContext context = new FileSystemXmlApplicationContext(path); AccountService accountService = context.getBean("accountService", AccountService.class);
5.5. ClassPathXmlApplicationContext
In case we want to load an XML configuration file from the classpath, we can use the ClassPathXmlApplicationContext class. Similar to FileSystemXMLApplicationContext, it's useful for test harnesses as well as for application contexts embedded within JARs.
So, let's see an example of using this class:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext/account-bean-config.xml"); AccountService accountService = context.getBean("accountService", AccountService.class);
6. Additional Features of ApplicationContext
6.1. Message Resolution
The ApplicationContext interface supports message resolution and internationalization by extending the MessageSource interface. Furthermore, Spring provides two MessageSource implementations, ResourceBundleMessageSource and StaticMessageSource.
We can use the StaticMessageSource to programmatically add messages to the source. However, it supports basic internationalization and is more suitable for tests than production use.
On the other hand, ResourceBundleMessageSource is the most common implementation of MessageSource. It relies on the underlying JDK's ResouceBundle implementation. It also uses the JDK's standard message parsing provided by MessageFormat.
Now, let's see how can we use the MessageSource to read the messages from a properties file.
First, we'll create the messages.properties file on the classpath:
account.name=TestAccount
Second, we'll add a bean definition in our AccountConfig class:
@Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("config/messages"); return messageSource; }
Third, we'll inject the MessageSource in the AccountService:
@Autowired private MessageSource messageSource;
Finally, we can use the getMessage method anywhere in the AccountService to read the message:
messageSource.getMessage("account.name", null, Locale.ENGLISH);
Spring also provides the ReloadableResourceBundleMessageSource class, which allows for reading files from any Spring resource location and supports hot reloading of bundle property files.
6.2. Event Handling
ApplicationContext supports event handling with the help of the ApplicationEvent class and the ApplicationListener interface. It supports built-in events like ContextStartedEvent, ContextStoppedEvent, ContextClosedEvent, and RequestHandledEvent. Moreover, it also supports custom events for business use cases.
7. Conclusion
In this tutorial, we've discussed various aspects of the ApplicationContext container in Spring. We've seen different examples of how to configure Spring beans in an AppicationContext. Also, we've seen how to create and use different types of ApplicationContext.
Seperti biasa, kod lengkap boleh didapati di GitHub.