您的位置:首页 > 编程语言 > Java开发

【SpringBoot基础】Aware框架 Bean获取资源调度

2019-04-04 16:31 821 查看

【SpringBoot基础】Aware框架 Bean获取资源调度

内容概要

Aware框架 :
原:bean注册到容器中,容器调用服务进行整合。
Aware: 使Bean获得容器的相关功能。
共6个接口
BeanNameAware : 获取容器中 Bean的名称
ResourceLoaderAware: 获取资源加载器,读取外部资源
BeanFactoryAware : 获取当前bean factory
MessageSourceAware: 获取messagesource ,可获取文本信息
ApplicationEventPublisherAware : 获得事件发布功能
ApplicationContextAware: 获取容器中的所有资源

文件结构


test.txt 内容

调用Bean类 AwareService

package com.Aware;

import org.apache.commons.io.IOUtils;
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;
/*Aware框架 :原:bean注册到容器中,容器调用服务整合。
Aware: 使Bean获得容器的相关功能。
BeanNameAware : 获取容器中 Bean的名称
ResourceLoaderAware: 获取资源加载器,读取外部资源
BeanFactoryAware : 获取当前bean factory
MessageSourceAware: 获取messagesource ,可获取文本信息
ApplicationEventPublisherAware : 获得事件发布功能
ApplicationContextAware: 获取容器中的所有资源
*/
@Service
public class AwareService implements BeanNameAware,ResourceLoaderAware {
private String name;  //bean 名称
private ResourceLoader loader; //加载器

public void setBeanName(String name) {
this.name = name;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.loader = resourceLoader;
}
public void  sayResult(){
System.out.println(name);
//加载文件
Resource resource = loader.getResource("txt/test.txt");
try {
System.out.println("Resource 加载内容:"+IOUtils.toString(resource.getInputStream()));
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}

配置类 AwareConfig

package com.Aware;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.Aware")
public class AwareConfig {
}

测试类 Main

package com.Aware;

import org.spr
20000
ingframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

public static void main(String[]args){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
AwareService bean = context.getBean(AwareService.class);
bean.sayResult();
context.close();
}
}

输出显示

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: