Spring学习--8 aware

Spring Aware

spring aware包括BeanNameAware、BeanFactoryAware、ApplicationContextAware、MessageSourceAware、ApplicationEventPublisherAware、ResourceLoaderAware等,采用spring aware可获取Spring容器本身的功能资源,不利之处在于将Bean与Spring框架进行了耦合。由于ApplicationContext接口继承了其他几类接口,因此通过ApplicationContextAware可获取Spring容器的所有服务,但原则上用什么接口就实现什么接口。
测试实例:

1. 在classpath下新建一个test.txt,内容随意,供资源加载用

2.Spring Aware Bean

package com.aware;

import java.io.IOException;

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;

@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {
    private String beanName;
    private ResourceLoader loader;

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

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    public void printResult() throws IOException {
        System.out.println("Bean name is: " + this.beanName);

        Resource resource = this.loader.getResource("classpath:com/aware/test.txt");
        System.out.println(IOUtils.toString(resource.getInputStream()));

    }
}

3.Configuration

package com.aware;

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

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

}

4.测试类

package com.aware;

import java.io.IOException;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Bootrap {
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AwareConfig.class);

    AwareService service = context.getBean(AwareService.class);
    service.printResult();

    context.close();
}

}

猜你喜欢

转载自blog.csdn.net/xiewz1112/article/details/80487981