思维导图
前言
Spring的依赖注入的最大亮点是你的所有的Bean对Spring容器的存在是没有意识的。
实际项目中,不可避免的用到Spring容器本身的功能资源,这时Bean必须要意识到Spring容器的存在,才能调用Spring所提供的的资源,这就是SpringAware
接口
名称 | 描述 |
---|---|
BeanNameAware | 获取容器中Bean的名称 |
BeanFactoryAwa | 获取当前Bean factory,这样可以调用容器的服务。 |
ApplicationContextAware | 当前application context,这样可以调用容器的服务 |
MessageSourceAware | 获得message source,这样合影获得文本信息 |
ApplicationEventPublisherAware | 应用时间发不起,可以发布事件 |
ResourceLoaderAware | 获取资源加载器,可以获得外部资源文件。 |
目的
是为了让Bean获得Spring容器的服务。
code demo
- 配置类
package com.example.demo.ch3.aware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.example.demo.ch3.aware")
public class AwareConfig {
}
- service组件
package com.example.demo.ch3.aware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {
private String beanName;
private ResourceLoader loader;
@Override
public void setBeanName(String s) {
beanName = s;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
resourceLoader = loader;
}
public void outputResult() {
System.out.println("Bean 的名称为:" + beanName);
}
}
- Main
package com.example.demo.ch3.aware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
AwareService awareService = context.getBean(AwareService.class);
awareService.outputResult();
context.close();
}
}