【Spring】 (7)加载外部资源txt,获取 当前bean名称

package com.example.demo_3_1;

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;

import java.io.IOException;

/**
 * Created by WangBin on 2017/4/18.
 *
 */
@Service
public class AwareService implements BeanNameAware,ResourceLoaderAware{//实现 BeanNameAware,ResourceLoaderAware 接口 获得Bean 名称和资源加载的服务
    private String beanName;
    private ResourceLoader loader;
    @Override
    public void setBeanName(String s) {//实现BeanNameAware需要重写setBeanName方法
        this.beanName = s;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {//实现ResourceLoaderAware 需要重写setResourceLoader 方法
        this.loader=resourceLoader;
    }

    public void outputResult(){
        System.err.println("Bean名称为"+beanName);
        Resource resource = loader.getResource("classpath:test.txt");
        try {
            System.err.println("ResourceLoader加载的文件内容为:"+ IOUtils.toString(resource.getInputStream(),"UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

package com.example.demo_3_1;

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

/**
 * Created by WangBin on 2017/4/18.
 *
 */
@Configuration
@ComponentScan("com.example.demo_3_1")
public class AwareConfig {
}

package com.example.demo_3_1;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by WangBin on 2017/4/18.
 *
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
        AwareService awareService = context.getBean(AwareService.class);
        awareService.outputResult();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值