Spring Aware的学习

Spring Aware

介绍

Spring的依赖注入的最大亮点就是你所有的Bean对Spring容器的存在是没有意识的。即你可以将你的容器替换成别的容器,例如Goggle Guice,这时Bean之间的耦合度很低。

但是在实际的项目中,我们不可避免的要用到Spring容器本身的功能资源,这时候Bean必须要意识到Spring容器的存在,才能调用Spring所提供的资源,这就是所谓的Spring Aware。其实Spring Aware本来就是Spring设计用来框架内部使用的,若使用了Spring Aware,你的Bean将会和Spring框架耦合。

Spring Aware 的目的是为了让Bean获得Spring容器的服务。因为ApplicationContext接口继承了messageSource的接口、ApplicationPublisher接口和ResouceLoader接口,所以Bean继承了ApplicationContextAware接口可以获得Spring容器的所有服务。

代码
package ch3.aware;

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

@Configuration
@ComponentScan("ch3.aware")
public class AwareConfig {
}
package ch3.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;

import java.io.IOException;

@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {
   private String beanName;
   private ResourceLoader loader;
   @Override
   public void setBeanName(String s) {
       this.beanName = s;
   }

   @Override
   public void setResourceLoader(ResourceLoader resourceLoader) {
       this.loader = resourceLoader;
   }
   public  void outputResult() {
       System.out.println("Bean的名称为:" +beanName);
       Resource resource = loader.getResource("classpath:test.txt");
       try{
           System.out.println("加载的文件内容为:"+ IOUtils.toString(resource.getInputStream())); // 工具类快速读取文件内容名。
       }catch (IOException e) {
           e.printStackTrace();
       }
   }
}

package 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();
    }
}

注意
  1. 应该把text.txt放到resource里面。
  2. Config文件一定不要忘了添加@Configurstion注解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值