Spring Aware

          Spring依赖注入的亮点就是所有的bean对spring容器的存在是没有意识的,即你可以将你的容器替换成其他的容器,如Google Guice,这是bean之间耦合度很低。

          但是在实际尅发中,我们不可避免的要用到spring容器本身的资源,这是你的bean必须要意识到spring容器的存在,才能调用spring所提供的资源,这就是所谓的spring aware,其实spring aware本来就是spring设计用来框架内部使用的,若使用spring aware,你的bean将会和spring框架耦合。

spring提供的Aware接口有多种   具体百度!

        spring Aware的目的是为了让bean获得spring容器的服务。

以下示例:Spring 演示Bean

自定义一个AwareService类实现BeanNameAware,ResourceLoaderAware接口:

package com.wisely.highlight_spring4.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;

/**
 * Spring Aware study
 * @author lulu.wang.o
 * @date 2019-05-09
 *
 * BeanNameAware:获取到容器中bean的名称
 * ResourceLoaderAware:获取资源加载器,可以获取外部资源文件
 */
@Service
public class AwareService implements BeanNameAware,ResourceLoaderAware{
	
	private String beanName;//bean的名称
	private ResourceLoader loader;//资源加载器

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.loader = resourceLoader;
	}

	@Override
	public void setBeanName(String name) {
		this.beanName = name;
	}
	
	public void outPutResult(){
		System.err.println("bean的名稱"+beanName);
		//获取资源
		Resource resource = loader.getResource("classpath:com/wisely/highlight_spring4/ch3/aware/test.txt");
		try {
			System.err.println("ResourceLoader 加载文件的内容为:"+ IOUtils.toString(resource.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

配置类:

package com.wisely.highlight_spring4.ch3.aware;

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

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.aware")
public class AwareConfig {

}

运行:

package com.wisely.highlight_spring4.ch3.aware;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AwareMain {
	
	
	public static void main(String[] args) {
		//使用AnnotationConfigApplicationContext作为Spring容器加载一个配置类作为参数
		AnnotationConfigApplicationContext applicationContext = 
				new AnnotationConfigApplicationContext(AwareConfig.class);
		//获取生命配置的bean
		AwareService awareService = applicationContext.getBean(AwareService.class);
		awareService.outPutResult();
		//关闭
		applicationContext.close();
	}

}

 

运行结果:

Spring Aware_第1张图片

你可能感兴趣的:(Spring)