In this paper, the content

  1. Contrast the BeanFactory ApplicationContext

  2. The extensibility of ApplicationContext

  3. internationalization

Contrast the BeanFactory ApplicationContext

A simple comparison of the function positioning of the two:

  • The BeanFactory provides the basic functionality to manage and manipulate beans, providing the underlying foundation for Spring’s IoC functionality for integration with the rest of Spring and related third-party frameworks
  • ApplicationContext extends other interfaces on top of BeanFactory to provide additional functionality for application frameworks and enterprise development.

The following table lists the capabilities provided by the BeanFactory and ApplicationContext interfaces and implementations.

features BeanFactory ApplicationContext
Bean instantiation and property injection Yes Yes
Life cycle management No Yes
BeanPostProcessorAutomatic registration No Yes
BeanFactoryPotProcessorAutomatic registration No Yes
internationalizationMessageSource No Yes
The built-inApplicationEventRelease mechanism No Yes

Because the ApplicationContext contains all of the functionality of a BeanFactory, it is generally recommended to use it instead of a regular BeanFactory unless you need to have complete control over the bean processing scenarios.

The extensibility of ApplicationContext

Discussed above the org. Springframework. Beans. Factory package provides the basic function of management and operating bean, including programmatically. Org. Springframework. Context package added ApplicationContext interface, it extends the BeanFactory interface, and also expanded the other interfaces, in the form of more geared to the needs of the application framework to provide additional functionality.

  • Internationalization: Access messages in I18N mode through the MessageSource interface
  • Access resources, such as urls and files, through the ResourceLoader interface
  • Event publishing, that is, through the use of ApplicationEventPublisher interface to realize interface ApplicationListener bean
  • HierarchicalBeanFactory Interface loads multiple (hierarchical) contexts, each focusing on a specific layer, such as the Web layer of an application

Internationalization MessageSource

The ApplicationContext interface extends an interface called MessageSource and therefore provides internationalization (” i18N “) functionality.

The MessageSource interface is defined and the main methods are as follows

public interface MessageSource {
    // Get messages: code message key args support {} default default value loC language
	String getMessage(String code, Object[] args, String default, Locale loc);
    String getMessage(String code, Object[] args, Locale loc)
	String getMessage(String code, Object[] args, Locale loc)
}
Copy the code

The java.util.Locale object represents a specific geographic, political, or cultural region. For example, China is zh

Find the process of loading a MessageSource in Spring

  • When the ApplicationContext is loaded, it automatically searches for MessageSource Beans defined in the context. The bean must have a name messageSource.
  • If such a bean is found, all calls to the above methods are delegated to the message source.
  • If the message source is not found, ApplicationContext will try to find the parent class containing the bean with the same name. If so, use the bean as a MessageSource.
  • If ApplicationContext does not find any message sources, instantiate an empty DelegatingMessageSource to accept calls to the methods defined above.

MessageSource implementation

Spring provides three MessageSource implementations:

  • ResourceBundleMessageSource

    Using the specified base name to access the ResourceBundle, this class relies on the underlying JDK’s ResourceBundle implementation in combination with the JDK standard message parsing provided by MessageFormat.

  • ReloadableResourceBundleMessageSource

    A spring-specific implementation that accesses the resource bundle using the specified base name and participates in the resource loading of Spring.ApplicationContext. Compared with the JDK based ResourceBundleMessageSource, the class using Java. Util. Properties instance as a custom message data structure, Through the Spring handle to the Resource of org. Springframework. Util. PropertiesPersister strategy to load them. This policy can not only reload files based on timestamp changes, but also load properties files with specific character encodings. It will also detect XML properties files.

  • StaticMessageSource.

    A simple implementation of MessageSource that allows messages to be registered programmatically. This MessageSource supports basic internationalization. Used for testing rather than production systems.

They all realized HierarchicalMessageSource for nested messaging.

Resource related knowledge points have been arranged in the subsequent articles

Integrated case

Provide a ResourceBundleMessageSource case, easy to understand.

  1. Classpath defines internationalization resource files, defining default and Chinese

    The demo16/ Exceptions_en.properties file, which supports {.. } placeholder content replacement

    argument.required=The {0} argument is required.
    Copy the code

    Demo16 / exceptions_zh. The properties file

    argument.required=The {0} argument is required.
    Copy the code

    Demo16 / format_zh. The properties file

    message=Chinese news
    Copy the code

    Demo16 / format_en. The properties file

    message=en
    Copy the code
  2. Injection ResourceBundleMessageSource instance, the name for messageSource

    @Configuration
    @ComponentScan
    public class AppConfig {
    
        @Bean("messageSource")
        public ResourceBundleMessageSource messageSource(a) {
            ResourceBundleMessageSource source = new ResourceBundleMessageSource();
            // Set the resource file in the classpath
            source.setBasenames("demo16/format"."demo16/exceptions"."demo16/windows");
            returnsource; }}Copy the code
  3. Used by calling the MessageSource interface method in the bean

    @Component
    public class MyBean {
        @Autowired
        private MessageSource messageSource;
    
        // Get the message content
        public void execute(a) {
            System.out.println("Get message content :");
            String message = this.messageSource.getMessage("message".null."Default", Locale.ENGLISH);
            System.out.println(message);
        }
    
        // Replace placeholder content as a string
        public void execute1(a) {
            System.out.println("Replace placeholder content string form:");
            String message = this.messageSource.getMessage("argument.required".new Object[]{"messageSource"},
                    "Required", Locale.ENGLISH);
            System.out.println(message);
        }
    
    
        // Get a Message in Chinese
        public void getChinesMessage(a) {
            System.out.println("Replace placeholder content in string form, language is Chinese:");
            String message = this.messageSource.getMessage("argument.required".new Object[]{"messageSource"},
                    "Required", Locale.CHINESE); System.out.println(message); }}Copy the code
  4. Test and observe the results

    @Test
    public void test1(a) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AppConfig.class);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.execute();
        myBean.execute1();
        myBean.getChinesMessage();
    }
    Copy the code
    String form: The messageSource argument is required. Replace placeholder content in string form, language is Chinese: messageSource parameter is required.Copy the code

    You can already switch internationalization based on language

conclusion

This article introduces the comparison between Spring’s BeanFactory and AppplicationContext, focusing on the internationalization of the AppplicationContext extension.

This source code address: github.com/kongxubihai… Knowledge sharing, reproduced please indicate the source. Learning has no priority, the first!