EnvironmentCapable、EnvironmentAware和Application-ContextAware


Spring中一些对于阅读源码有用的知识:

 

这三个类直接实现三个接口:EnvironmentCapable、EnvironmentAware和Application-ContextAware。

  XXXAware在spring里表示对XXX可以感知,通俗点解释就是:

  如果在某个类里面想要使用spring的一些东西,就可以通过实现XXXAware接口告诉spring,spring看到后就会给你送过来,而接收的方式是通过实现接口唯一的方法set-XXX。

  比如,有一个类想要使用当前的ApplicationContext,那么我们只需要让它实现ApplicationContextAware接口,然后实现接口中唯一的方法void setApplicationContext(ApplicationContext applicationContext)就可以了,spring会自动调用这个方法将applicationContext传给我们,我们只需要接收就可以了!很方便吧!

  EnvironmentCapable,顾名思义,当然就是具有Environment的能力,也就是可以提供Environment,所以EnvironmentCapable唯一的方法是Environment getEnvironment(),用于实现EnvironmentCapable接口的类,就是告诉spring它可以提供Environment,当spring需要Environment的时候就会调用其getEnvironment方法跟它要

 

public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware
public abstract class FrameworkServlet extends HttpServletBean implements ApplicationContextAware

在HttpServletBean 和FrameworkServlet 中出现的和EnvironmentCapable、EnvironmentAware和Application-ContextAware有关的代码:

public interface ApplicationContextAware extends Aware {
    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

public interface EnvironmentCapable {
    Environment getEnvironment();
}

public interface EnvironmentAware extends Aware {
    void setEnvironment(Environment environment);
}

org.springframework.web.servlet.HttpServletBean#setEnvironment

    @Override
    public void setEnvironment(Environment environment) {
        Assert.isInstanceOf(ConfigurableEnvironment.class, environment, "ConfigurableEnvironment required");
        this.environment = (ConfigurableEnvironment) environment;
    }

org.springframework.web.servlet.HttpServletBean#getEnvironment

    @Override
    public ConfigurableEnvironment getEnvironment() {
        if (this.environment == null) {
            this.environment = createEnvironment();
        }
        return this.environment;
    }

org.springframework.web.servlet.FrameworkServlet#setApplicationContext

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (this.webApplicationContext == null && applicationContext instanceof WebApplicationContext) {
            this.webApplicationContext = (WebApplicationContext) applicationContext;
            this.webApplicationContextInjected = true;
        }
    }

来自《springmvc源码》

 

EnvironmentCapable、EnvironmentAware和Application-ContextAware

上一篇:jenkins publish .net core application to linux server


下一篇:Android中jsoup的混淆规则【转】