Aware
接口介绍
在Spring框架中,Aware
接口是一种特殊类型的接口,它们用于在Spring容器创建bean时,自动注入某些依赖。这些接口允许bean知道Spring容器的某些特定上下文信息。例如,BeanNameAware
接口允许bean知道它在Spring容器中的名
接口路径:org.springframework.beans.factory.Aware
常见的Aware
接口
以下是一些常见的Aware
接口及其作用:
ApplicationContextAware
- 作用: 实现该接口的Bean可以获取到
ApplicationContext
对象,从而可以访问Spring容器中的其他Bean。 - 方法:
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
BeanFactoryAware
- 作用: 实现该接口的Bean可以获取到
BeanFactory
对象,从而可以访问Spring容器中的其他Bean。 - 方法:
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
BeanNameAware
- 作用: 实现该接口的Bean可以获取到自己在Spring容器中的Bean名称。
- 方法:
void setBeanName(String name);
ResourceLoaderAware
- 作用: 实现该接口的Bean可以获取到
ResourceLoader
对象,从而可以加载资源文件。 - 方法:
void setResourceLoader(ResourceLoader resourceLoader);
MessageSourceAware
- 作用: 实现该接口的Bean可以获取到
MessageSource
对象,从而可以解析国际化消息。 - 方法:
void setMessageSource(MessageSource messageSource);
ApplicationEventPublisherAware
- 作用: 实现该接口的Bean可以获取到
ApplicationEventPublisher
对象,从而可以发布Spring事件。 - 方法:
void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher);
EnvironmentAware
- 作用: 实现该接口的Bean可以获取到
Environment
对象,从而可以访问Spring的环境配置。 - 方法:
void setEnvironment(Environment environment);
ServletContextAware
- 作用: 实现该接口的Bean可以获取到
ServletContext
对象,从而可以访问Servlet容器的上下文。 - 方法:
void setServletContext(ServletContext servletContext);
代码示例
demoBean
类实现了ApplicationContextAware
接口,并通过setApplicationContext
方法获取到了ApplicationContext
对象。这样,demoBean
就可以在运行时访问Spring容器中的TestBean (其他Bean)。
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class DemoBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void doSomething() {
// 使用applicationContext获取TestBean
TestBean testrBean = applicationContext.getBean(TestBean .class);
anotherBean.doSomethingElse();
}
}
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
@Component
public class DemoServletContextAwareBean implements ServletContextAware {
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public void doSomethingWithServletContext() {
String contextPath = servletContext.getContextPath();
System.out.println("Web应用程序上下文路径 : " + contextPath);
String initParam = servletContext.getInitParameter("myInitParam");
System.out.println("初始化参数: " + initParam);
}
}