Spring高級話題-Aware

一、Aware是什麼?

Spring Aware就是一些定義了Spring容器本身功能資源的接口

Spring提供的Aware接口
接口 備註
BeanNameAware 獲得到容器中Bean的名稱
BeanFactoryAware 獲得當前 bean factory,這樣可以調用容器的服務
ApplicationContextaware* 當前的 application context,這樣可以調用容器的服務
MessageSourceAware 獲得 message source,這樣可以獲得文本信息
ApplicationEventPublisherAware 應用事件發佈器,可以發佈事件
ResourceLoaderAware 獲得資源加載器,可以獲得外部資源文件

二、什麼時候用Aware

當某一個Bean需要獲得Spring容器的服務時,可以實現對應的Aware接口。
注意: 這樣會造成Bean與Spring框架的耦合性增加

三、AwareDemo

bean

package com.cactus.demo.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;

/**
 * Created by liruigao
 * Date: 2019-12-05 14:35
 * Description:
 */

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

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

    public void show() {
        System.out.println("beanName : " + beanName);
        Resource resource = resourceLoader.getResource("classpath:awaredemo/awaredemo.txt");
        String desc = resource.getDescription();
        System.out.println("resource desc : " + desc);
        try {
            String streamStr = IOUtils.toString(resource.getInputStream(), "utf-8");
            System.out.println("resource streamStr : " + streamStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

配置類

package com.cactus.demo.aware;

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

/**
 * Created by liruigao
 * Date: 2019-12-05 14:43
 * Description:
 */

@Configuration
@ComponentScan("com.cactus.demo.aware")
public class AwareConfig {
}

awaredemo.txt

this is a awaredemo!

Main

package com.cactus.demo.aware;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by liruigao
 * Date: 2019-12-05 14:45
 * Description:
 */


public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
        AwareDemo awareDemo = context.getBean(AwareDemo.class);
        awareDemo.show();
        context.close();
    }
}

Result

beanName : awareDemo
resource desc : class path resource [awaredemo/awaredemo.txt]
resource streamStr : this is a awaredemo!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章