What is Spring Aware

Spring provides an Aware interface to make beans Aware of the existence of the Spring container, that is, to make beans use of resources provided by the Spring container.

Classification of Spring Aware

Several common Aware interfaces are as follows.

Aware interface instructions
ApplicationContextAware Can get the service that the Application Context calls the container
ApplicationEventPublisherAware Apply an event publisher that can be used to publish events
BeanClassLoaderAware Can get the class loader that loads the current Bean
BeanFactoryAware Can get the Bean Factory call container’s service
BeanNameAware Can get the name of the current Bean
EnvironmentAware Gets information about the environment properties of the current container
MessageSourceAware Access to internationalized text information
ResourceLoaderAware Get resource loader reads resource files
ServletConfigAware ServletConfig is available
ServletContextAware You can get the ServletContext

You can see more of its inheritance diagram.

Use of Spring Aware

To get a Bean from a container, you can inherit ApplicationContextAware and give the Bean the ability to call the container’s services.

import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringAppContext implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringAppContext.applicationContext == null) { SpringAppContext.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) { return getApplicationContext().getBean(name); } public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); }}Copy the code

Welcome to forward to moments, and friends together to improve themselves.

Recommended reading

Dry goods: Free 2TB architect four-stage video tutorial

Interview: the most complete Java multithreaded interview questions and answers

Tools: Recommended an online creation flow chart, mind mapping software

Share Java dry goods, high concurrency programming, hot technology tutorials, microservices and distributed technology, architecture design, blockchain technology, artificial intelligence, big data, Java interview questions, and cutting-edge hot news.