ApplicationContext

The ApplicationContext container provides support to access application components using BeanFactory methods. This includes all functionality of BeanFactory. In addition, ApplicationContext can also perform more enterprise functionalities, like transaction, AOP, resolving text messages from properties files, and pushing application events to interested listeners. It also has the ability to publish events to the registered listeners.

The mostly-used implementations of ApplicationContext are FileSystemXmlApplicationContext, ClassPathXmlApplicationContext, and AnnotationConfigApplicationContext.

Spring also provides us with a web-aware implementation of the ApplicationContext interface, as shown:

  • XmlWebApplicationContext
  • AnnotationConfigWebApplicationContext

We can use either one of these implementations to load beans into a BeanFactory; it depends upon our application configuration file locations. For example, if we want to load our configuration file Beans.xml from the filesystem in a specific location, we can use a FileSystemXmlApplicationContext class that looks for the configuration file Beans.xml in a specific location within the filesystem:

ApplicationContext context = new
FileSystemXmlApplicationContext("E:/Spring/Beans.xml");

If we want to load our configuration file Beans.xml from the classpath of our application, we can use ClassPathXmlApplicationContext class provided by Spring. This class looks for the configuration file Beans.xml anywhere in the classpath, including JAR files:

ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");

If you are using a Java configuration instead of an XML configuration, you can use AnnotationConfigApplicationContext:

ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);

After loading the configuration files and getting an ApplicationContext, we can fetch beans from the Spring container by calling the getBean() method of the ApplicationContext:

BankAccountService bankAccountService =
context.getBean(BankAccountService.class);

In the following section, we will learn about the Spring bean life cycle, and how a Spring container reacts to the Spring bean to create and manage it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset