Aware interface and application scenarios in Spring

The Aware interface is a set of marker interfaces provided in the Spring Framework, which is used to obtain information such as some core components or runtime context provided in the Spring container during the Bean assembly process. By using the Aware interface, we can obtain other components in the Spring container during the Bean instantiation and initialization process, which facilitates the Bean class to implement more complex business logic.

This article will introduce each Aware interface in Spring one by one, and the main application scenarios of these interfaces.

1. ApplicationContextAware

The ApplicationContextAware interface allows the Bean to obtain the ApplicationContext object. Through this object, we can obtain other Bean instances or some components in the Spring container. Common application scenarios include:

  • Get ServletContext in web project
  • Get Internationalization Information
  • Obtain scheduled tasks such as Scheduler

Sample code:

public class MyBean implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void doSomething() {
        // 获取其他的Bean实例或其他的组件
        OtherBean otherBean = applicationContext.getBean("otherBean", OtherBean.class);
        // ...
    }
}
复制代码

2. BeanFactoryAware

The BeanFactoryAware interface allows the Bean to obtain the BeanFactory object. Through this object, we can obtain the Bean instance or some components in the Spring container. Common application scenarios include:

  • Get the Bean instance in the Spring container
  • Register BeanDefinition manually

Sample code:

public class MyBean implements BeanFactoryAware {
    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public void doSomething() {
        // 获取其他的Bean实例或其他的组件
        OtherBean otherBean = beanFactory.getBean("otherBean", OtherBean.class);
        // ...
    }
}
复制代码

3. MessageSourceAware

The MessageSourceAware interface allows the Bean to obtain the MessageSource object. Through this object, we can easily perform internationalization operations. Common application scenarios include:

  • Get Internationalization Information

Sample code:

public class MyBean implements MessageSourceAware {
    private MessageSource messageSource;

    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public void doSomething() {
        // 获取国际化信息
        String message = messageSource.getMessage("key", null, Locale.getDefault());
        // ...
    }
}
复制代码

4. ResourceLoaderAware

The ResourceLoaderAware interface allows the Bean to obtain the ResourceLoader object, through which we can conveniently perform resource loading operations. Common application scenarios include:

  • load configuration file
  • Load static resources such as pictures

Sample code:

public class MyBean implements ResourceLoaderAware {
    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public void doSomething() {
        // 加载配置文件
        Resource resource = resourceLoader.getResource("classpath:config.xml");
        // ...
    }
}
复制代码

5. ServletContextAware

The ServletContextAware interface allows the Bean to obtain the ServletContext object. Through this object, we can easily develop Web projects. Common application scenarios include:

  • 获取Web项目的一些信息,如上下文路径等

示例代码:

public class MyBean implements ServletContextAware {
    private ServletContext servletContext;

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public void doSomething() {
        // 获取上下文路径
        String contextPath = servletContext.getContextPath();
        // ...
    }
}
复制代码

6. EnvironmentAware

EnvironmentAware接口可以让Bean获取到Environment对象,通过这个对象,我们可以方便地获取Spring的环境配置信息。常见的应用场景包括:

  • 获取当前的环境配置,如开发环境、测试环境或生产环境
  • 获取配置文件中的属性值

示例代码:

public class MyBean implements EnvironmentAware {
    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    public void doSomething() {
        // 获取当前环境
        String profile = environment.getActiveProfiles()[0];
        // 获取配置文件中的属性值
        String value = environment.getProperty("key");
        // ...
    }
}
复制代码

7. ServletConfigAware

ServletConfigAware接口可以让Bean获取到ServletConfig对象,通过这个对象,我们可以方便地获取Servlet的相关信息。常见的应用场景包括:

  • 获取Servlet的名称
  • 获取Servlet的初始化参数

示例代码:

public class MyServlet extends HttpServlet implements ServletConfigAware {
    private ServletConfig servletConfig;

    @Override
    public void setServletConfig(ServletConfig servletConfig) {
        this.servletConfig = servletConfig;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        // 获取Servlet的名称
        String servletName = servletConfig.getServletName();
        // 获取Servlet的初始化参数
        String value = servletConfig.getInitParameter("key");
        // ...
    }
}
复制代码

8. ApplicationContextInitializer

ApplicationContextInitializer接口是Spring提供的一个接口,我们可以在Spring容器初始化之前做一些必要的操作,常见的应用场景包括:

  • 修改配置信息
  • 注册BeanDefinition

示例代码:

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        // 注册BeanDefinition
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(OtherBean.class);
        beanDefinition.setPropertyValues(new MutablePropertyValues());
        ((DefaultListableBeanFactory) applicationContext.getBeanFactory()).registerBeanDefinition("otherBean", beanDefinition);
        // ...
    }
}
复制代码

9. EmbeddedValueResolverAware

EmbeddedValueResolverAware接口可以让Bean获取到EmbeddedValueResolver对象,通过这个对象,我们可以方便地替换属性占位符。常见的应用场景包括:

  • 替换配置文件中的占位符

示例代码:

public class MyBean implements EmbeddedValueResolverAware {
    private EmbeddedValueResolver embeddedValueResolver;

    @Override
    public void setEmbeddedValueResolver(EmbeddedValueResolver embeddedValueResolver) {
        this.embeddedValueResolver = embeddedValueResolver;
    }

    public void doSomething() {
        // 获取属性值
        String value = embeddedValueResolver.resolveStringValue("${key}");
        // ...
    }
}
复制代码

10. LoadTimeWeaverAware

LoadTimeWeaverAware接口可以让Bean获取到LoadTimeWeaver对象,通过这个对象,我们可以实现类的动态加载。常见的应用场景包括:

  • 动态加载类 示例代码:
public class MyBean implements LoadTimeWeaverAware {
    private LoadTimeWeaver loadTimeWeaver;

    @Override
    public void setLoadTimeWeaver(LoadTimeWeaver loadTimeWeaver) {
        this.loadTimeWeaver = loadTimeWeaver;
    }

    public void doSomething() {
        // 动态加载类
        ClassLoader classLoader = loadTimeWeaver.getClassLoader();
        Class<?> clazz = classLoader.loadClass("com.example.OtherClass");
        // ...
    }
}
复制代码

11. ApplicationEventPublisherAware

ApplicationEventPublisherAware接口可以让Bean获取到ApplicationEventPublisher对象,通过这个对象,我们可以方便地发布和监听事件。常见的应用场景包括:

  • 实现自定义事件
  • 监听Spring容器事件

示例代码:

public class MyBean implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    public void doSomething() {
        // 发布事件
        applicationEventPublisher.publishEvent(new MyEvent(this, "event data"));
        // ...
    }
}

@Component
public class MyEventListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent event) {
        // 处理事件
        // ...
    }
}
复制代码

12. ConversionServiceAware

ConversionServiceAware接口可以让Bean获取到ConversionService对象,通过这个对象,我们可以方便地进行类型转换。常见的应用场景包括:

  • 类型转换
  • 数据校验

示例代码:

public class MyBean implements ConversionServiceAware {
    private ConversionService conversionService;

    @Override
    public void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    public void doSomething() {
        // 类型转换
        String str = "123";
        Integer value = conversionService.convert(str, Integer.class);
        // ...
    }
}
复制代码

在使用Aware接口时,需要注意避免循环依赖和过度依赖的问题。另外,Aware接口的实现可以通过XML、注解或编程方式来实现。

以上就是Spring中各个Aware接口的应用场景和示例代码,希望对大家在实际开发中使用Spring有一定的帮助。

Guess you like

Origin juejin.im/post/7229485914219610173