spring的aware们

Aware是什么

spring框架提供了多个*Aware接口,用于辅助Spring Bean编程访问Spring容器。
通过实现这些接口,可以增强Spring Bean的功能,将一些特殊的spring内部bean暴露给业务应用。

  • ApplicationContextAware

将ApplicationContext暴露出来,使用最频繁的api为getBean方法,动态获取spring中的bean。spring2.5+之后可以不实现aware接口,直接@autowired注入到业务bean中直接使用。

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
        MessageSource, ApplicationEventPublisher, ResourcePatternResolver 
  • BeanFactoryAware

将BeanFactory暴露给用户,也可以直接@autowired注入。BeanFactory只声明了一些基本方法,如getBean,containsBean,isPrototype,isSingleton等,ApplicationContext继承了BeanFactory,它有自己的很多扩展方法(容器启动日期,容器id,他还实现了事件接口,可以发布事件等等)。

  • ApplicationEventPublisherAware

ApplicationEventPublisher可以发布事件,ApplicationContext也继承了该接口,可以直接使用ApplicationContext来发布。spring使用示例:

在使用Spring的事件支持时,我们需要关注以下几个对象:

  1. ApplicationEvent:继承自EventObject,同时是spring的application中事件的父类,需要被自定义的事件继承。 
  2. ApplicationListener:继承自EventListener,spring的application中的监听器必须实现的接口,需要被自定义的监听器实现其onApplicationEvent方法 
  3. ApplicationEventPublisherAware:在spring的context中希望能发布事件的类必须实现的接口,该接口中定义了设置ApplicationEventPublisher的方法,由ApplicationContext调用并设置。在自己实现的ApplicationEventPublisherAware子类中,需要有ApplicationEventPublisher属性的定义。 
  4. ApplicationEventPublisher:spring的事件发布者接口,定义了发布事件的接口方法publishEvent。因为ApplicationContext实现了该接口,因此spring的ApplicationContext实例具有发布事件的功能(publishEvent方法在AbstractApplicationContext中有实现)。在使用的时候,只需要把ApplicationEventPublisher的引用定义到ApplicationEventPublisherAware的实现中,spring容器会完成对ApplicationEventPublisher的注入。 

在spring的bean配置中,因为事件是由事件源发出的,不需要注册为bean由spring容器管理。所以在spring的配置中,只需配置自定义的ApplicationEventListener和publisherAware(即实现了ApplicationEventPublisherAware接口的发布类),而对于ApplicationEventPublisher的管理和注入都由容器来完成。

基于spring的事件简单实现如下:
定义ApplicationEvent

import org.springframework.context.ApplicationEvent;  
/** 
 * 定义Spring容器中的事件,与java普通的事件定义相比,只是继承的父类不同而已,在 
 * 在定义上并未有太大的区别,毕竟ApplicationEvent也是继承自EventObject的。 
 */  
public class MethodExecutionEvent extends ApplicationEvent {  
  
    private static final long serialVersionUID = 2565706247851725694L;  
    private String methodName;  
    private MethodExecutionStatus methodExecutionStatus;  
      
    public MethodExecutionEvent(Object source) {  
        super(source);  
    }  
      
    public MethodExecutionEvent(Object source, String methodName, MethodExecutionStatus methodExecutionStatus) {  
        super(source);  
        this.methodName = methodName;  
        this.methodExecutionStatus = methodExecutionStatus;  
    }  
  
    public String getMethodName() {  
        return methodName;  
    }  
  
    public void setMethodName(String methodName) {  
        this.methodName = methodName;  
    }  
  
    public MethodExecutionStatus getMethodExecutionStatus() {  
        return methodExecutionStatus;  
    }  
  
    public void setMethodExecutionStatus(MethodExecutionStatus methodExecutionStatus) {  
        this.methodExecutionStatus = methodExecutionStatus;  
    }  
}  

定义ApplicationEventListener

import org.springframework.context.ApplicationEvent;  
import org.springframework.context.ApplicationListener;  
  
import com.nuc.event.MethodExecutionEvent;  
import com.nuc.event.MethodExecutionStatus;  
/** 
 * Spring容器中的事件监听器,与java中基本的事件监听器的定义相比,这里需要实现ApplicationListener接口 
 * ApplicationListener接口虽然继承自EventListener,但扩展了EventListener 
 * 它在接口声明中定义了onApplicationEvent的接口方法,而不像EventListener只作为标记性接口。 
 */  
  
public class MethodExecutionEventListener implements ApplicationListener {  
  
    public void onApplicationEvent(ApplicationEvent event) {  
        if (event instanceof MethodExecutionEvent) {  
           if (MethodExecutionStatus.BEGIN  
                    .equals(((MethodExecutionEvent) event)  
                            .getMethodExecutionStatus())) {  
                System.out.println("It's beginning");  
            }  
            if (MethodExecutionStatus.END.equals(((MethodExecutionEvent) event).getMethodExecutionStatus())) {  
                System.out.println("It's ending");  
            }  
        }  
    }  
}  

定义ApplicationEventPublisherAware

import org.springframework.context.ApplicationEventPublisher;  
import org.springframework.context.ApplicationEventPublisherAware;  
  
import com.nuc.event.MethodExecutionEvent;  
import com.nuc.event.MethodExecutionStatus;  
  
public class MethodExecutionEventPublisher implements  
        ApplicationEventPublisherAware {  
  
    private ApplicationEventPublisher eventPublisher;  
      
    public void methodToMonitor() {  
        MethodExecutionEvent beginEvent = new MethodExecutionEvent(this, "methodToMonitor", MethodExecutionStatus.BEGIN);  
        this.eventPublisher.publishEvent(beginEvent);  
        //TODO  
        MethodExecutionEvent endEvent = new MethodExecutionEvent(this, "methodToMonitor", MethodExecutionStatus.END);  
        this.eventPublisher.publishEvent(endEvent);  
    }  
      
    public void setApplicationEventPublisher(  
            ApplicationEventPublisher applicationEventPublisher) {  
        this.eventPublisher = applicationEventPublisher;  
    }  
}  

定义bean配置

<?xml version="1.0" encoding="GBK"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"  
    default-autowire="byName">  
    <bean id="methodExecListener" class="com.nuc.listener.MethodExecutionEventListener"></bean>  
    <bean id="evtPublisher" class="com.nuc.publisher.MethodExecutionEventPublisher"></bean>   
</beans>  

使用事件

import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
  
import com.nuc.publisher.MethodExecutionEventPublisher;  
  
public class App   
{  
    public static void main( String[] args )  
    {  
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
        MethodExecutionEventPublisher publisher = (MethodExecutionEventPublisher)context.getBean("evtPublisher");  
        publisher.methodToMonitor();  
    }  
} 
  • BeanClassLoaderAware

实现该aware后spring会把加载业务bean类时使用的类加载器暴露出来。接口声明如下:

public interface BeanClassLoaderAware extends Aware {

    /**
     * Callback that supplies the bean {@link ClassLoader class loader} to
     * a bean instance.
     * <p>Invoked <i>after</i> the population of normal bean properties but
     * <i>before</i> an initialization callback such as
     * {@link InitializingBean InitializingBean's}
     * {@link InitializingBean#afterPropertiesSet()}
     * method or a custom init-method.
     * @param classLoader the owning class loader; may be {@code null} in
     * which case a default {@code ClassLoader} must be used, for example
     * the {@code ClassLoader} obtained via
     * {@link org.springframework.util.ClassUtils#getDefaultClassLoader()}
     */
    void setBeanClassLoader(ClassLoader classLoader);

}
  • BeanNameAware

将当前bean在spring中的beanname暴露出来。

lic interface BeanNameAware extends Aware {

    /**
     * Set the name of the bean in the bean factory that created this bean.
     * <p>Invoked after population of normal bean properties but before an
     * init callback such as {@link InitializingBean#afterPropertiesSet()}
     * or a custom init-method.
     * @param name the name of the bean in the factory.
     * Note that this name is the actual bean name used in the factory, which may
     * differ from the originally specified name: in particular for inner bean
     * names, the actual bean name might have been made unique through appending
     * "#..." suffixes. Use the {@link BeanFactoryUtils#originalBeanName(String)}
     * method to extract the original bean name (without suffix), if desired.
     */
    void setBeanName(String name);

}

Spring 自动调用。并且会在Spring自身完成Bean配置之后,且在调用任何Bean生命周期回调(初始化或者销毁)方法之前就调用这个方法。换言之,在程序中使用BeanFactory.getBean(String beanName)之前,Bean的名字就已经设定好了。所以,程序中可以尽情的使用BeanName而不用担心它没有被初始化。

  • BootstrapContextAware,资源适配器,不知道怎么用
  • EmbeddedValueResolverAware

应用配置文件读取辅助。他的读取方式需要加${xx.xx}这样的方式,使用示例:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;

@Component("propertiesUtils")
public class PropertiesUtils implements EmbeddedValueResolverAware {

    private StringValueResolver resolver = null;

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.resolver = resolver;
    }

    public String getPropertiesValue(String name) {
        return resolver.resolveStringValue(name);
    }
}

测试:

import com.google.common.collect.Maps;
import com.jd.caiyu.common.utils.PropertiesUtils;
import com.jd.caiyu.match.domain.agent.enums.AgentTypeEnum;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Map;

import static com.jd.caiyu.match.domain.agent.enums.AgentTypeEnum.PRIMARY;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring-config.xml")
public class PropertiesUtilsTest {

    @Autowired
    private PropertiesUtils propertiesUtils;

    @Test
    public void testGetValue(){
        String value = propertiesUtils.getPropertiesValue("${jmq.address}"); //注意访问方式

        Assert.assertEquals("查询结果与期待的不一致!!!", "192.168.179.66:50088", value);



        Map<AgentTypeEnum, String> map = Maps.newHashMap();

        map.put(PRIMARY, "xxx");
    }

}
  • EnvironmentAware
    Environment可以获取所有环境变量,包括应用的properties,使用示例:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
 
/**
 * 主要是@Configuration,实现接口:EnvironmentAware就能获取到系统环境信息
 */
@Configuration
public class MyEnvironmentAware implements EnvironmentAware{
 
       //注入application.properties的属性到指定变量中.
       @Value("${spring.datasource.url}")
       private String myUrl;
      
       /**
        *注意重写的方法 setEnvironment 是在系统启动的时候被执行。
        */
       @Override
       public void setEnvironment(Environment environment) {
             
              //打印注入的属性信息.
              System.out.println("myUrl="+myUrl);
             
              //通过 environment 获取到系统属性.
              System.out.println(environment.getProperty("JAVA_HOME"));
             
              //通过 environment 同样能获取到application.properties配置的属性.
              System.out.println(environment.getProperty("spring.datasource.url"));
             
              //获取到前缀是"spring.datasource." 的属性列表值.
              RelaxedPropertyResolver relaxedPropertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
              System.out.println("spring.datasource.url="+relaxedPropertyResolver.getProperty("url"));
       System.out.println("spring.datasource.driverClassName="+relaxedPropertyResolver.getProperty("driverClassName"));
       }
}

ApplicationContext也继承了该接口,所以可以直接使用ApplicationContext。
国际化使用示例:

首先定义一个messageSource:


<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> 
<beans> 
    <!-- 资源国际化测试 --> 
    <bean id="messageSource"        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">        <property name="basenames"> 
            <list> 
                <value>org/rjstudio/spring/properties/messages</value> 
            </list> 
        </property> 
    </bean> 
</beans> 

这个Bean的id是定死的,只能为“messageSource”。这里的Class需要填入MessageSource接口的实现。其中,在我看的书中只提及了两个类,一个是:ResourceBundleMessageSource,另一个则是ReloadableResourceBundleMessageSource。其中,后者提供了无需重启就可重新加载新配置的特性。
list节点的value子节点中的body值“org/rjstudio/spring/properties/messages”,是指org.rjstudio.spring.proerties包下的以messages为主要名称的properties文件。比如说,以Locale为zh_CN为例,Spring会自动在类路径中在org.rjstudio.spring.properties包下按照如下顺序搜寻配置文件并进行加载。

接下来,让我们在org.rjstudio.spring.properties下,建立两个messages的属性文件。一个名为messages_zh_CN.properties,另一个为messages_en_US.properties,分别对应国际化中的中国和美国。

在这两个属性文件中分别建立一个userinfo属性。 
    中国为:userinfo=当前登陆用户[{0}] 登陆时间[{1}] 
    美国为:userinfo=current login user:[{0}] login time:[{1}] 

好了,一切就绪,接下来可以写段代码来测试了。。建个类,写个测试Main方法。 
public class MessageTest { 
        public static void main(String[] args) { 
            ApplicationContext ctx = new ClassPathXmlApplicationContext("messages.xml"); 
            Object[] arg = new Object[] { "Erica", Calendar.getInstance().getTime() }; 
            String msg = ctx.getMessage("userinfo", arg,Locale.CHINA);  //使用中文资源配置
            System.out.println("Message is ===> " + msg); 
        } 
    } 
    
    //最后输出的结果是:Message is ===> 当前登录用户:[Erica] 登录时间:[07-6-8 上午10:20] 

ctx.getMessage("userinfo", arg,Locale.US);
/*这个方法,传入的三个参数,第一个是properties文件中对应的名。arg为一个对象数组,我们在properties里面放置了两个变量,[{0}]和[{1}],Spring会为我们给它们赋值。而最后则需要传入一个Local。这里用 Locale.CHINA代表中国。如果我们用Locale.US,则输出会变为: 
    
    Message is ===> current login user:[Erica] login time:[6/8/07 10:59 AM] 
*/
    
  • NotificationPublisherAware,jmx相关,后续深究
  • ResourceLoaderAware

资源加载器注入,ApplicationContext也实现了ResourceLoader.
在Spring里面还定义有一个ResourceLoader接口,该接口中只定义了一个用于获取Resource的getResource(String location)方法。它的实现类有很多,这里我们先挑一个DefaultResourceLoader来讲。DefaultResourceLoader在获取Resource时采用的是这样的策略:首先判断指定的location是否含有“classpath:”前缀,如果有则把location去掉“classpath:”前缀返回对应的ClassPathResource;否则就把它当做一个URL来处理,封装成一个UrlResource进行返回;如果当成URL处理也失败的话就把location对应的资源当成是一个ClassPathResource进行返回。

@Test  
public void testResourceLoader() {  
   ResourceLoader loader = new DefaultResourceLoader();  
   Resource resource = loader.getResource("http://www.google.com.hk");  
   System.out.println(resource instanceof UrlResource); //true  
   //注意这里前缀不能使用“classpath*:”,这样不能真正访问到对应的资源,exists()返回false  
   resource = loader.getResource("classpath:test.txt");  
   System.out.println(resource instanceof ClassPathResource); //true  
   resource = loader.getResource("test.txt");  
   System.out.println(resource instanceof ClassPathResource); //true  
}

ApplicationContext接口也继承了ResourceLoader接口,所以它的所有实现类都实现了ResourceLoader接口,都可以用来获取Resource。
对于ClassPathXmlApplicationContext而言,它在获取Resource时继承的是它的父类DefaultResourceLoader的策略。
FileSystemXmlApplicationContext也继承了DefaultResourceLoader,但是它重写了DefaultResourceLoader的getResourceByPath(String path)方法。所以它在获取资源文件时首先也是判断指定的location是否包含“classpath:”前缀,如果包含,则把location中“classpath:”前缀后的资源从类路径下获取出来,当做一个ClassPathResource;否则,继续尝试把location封装成一个URL,返回对应的UrlResource;如果还是失败,则把location指定位置的资源当做一个FileSystemResource进行返回。

  • ServletConfigAware
public interface ServletConfig {
    

    /**
     * Returns the name of this servlet instance.
     * The name may be provided via server administration, assigned in the 
     * web application deployment descriptor, or for an unregistered (and thus
     * unnamed) servlet instance it will be the servlet's class name.
     *
     * @return      the name of the servlet instance
     *
     *
     *
     */

    public String getServletName();

    /**
     * Returns a reference to the {@link ServletContext} in which the caller
     * is executing.
     *
     *
     * @return      a {@link ServletContext} object, used
     *          by the caller to interact with its servlet 
     *                  container
     * 
     * @see     ServletContext
     *
     */

    public ServletContext getServletContext();
    
    /**
     * Returns a <code>String</code> containing the value of the 
     * named initialization parameter, or <code>null</code> if 
     * the parameter does not exist.
     *
     * @param name  a <code>String</code> specifying the name
     *          of the initialization parameter
     *
     * @return      a <code>String</code> containing the value 
     *          of the initialization parameter
     *
     */

    public String getInitParameter(String name);


    /**
     * Returns the names of the servlet's initialization parameters
     * as an <code>Enumeration</code> of <code>String</code> objects, 
     * or an empty <code>Enumeration</code> if the servlet has
     * no initialization parameters.
     *
     * @return      an <code>Enumeration</code> of <code>String</code> 
     *          objects containing the names of the servlet's 
     *          initialization parameters
     *
     *
     *
     */

    public Enumeration getInitParameterNames();


}
  • ServletContextAware,注入ServletContext

【ServletContext的5大作用】
ServletContext,是一个全局的储存信息的空间,服务器开始,其就存在,服务器关闭,其才释放。request,一个用户可有多个;session,一个用户一个;而servletContext,所有用户共用一个。所以,为了节省空间,提高效率,ServletContext中,要放必须的、重要的、所有用户需要共享的线程又是安全的一些信息。
1.获取web的上下文路径

String getContextPath();

2.获取全局的参数

String getInitParameter(String name);

Enumeration getInitParameterNames();

3.和域对象相关的

void setAttribute(String name,Onject object);

Object getAttribute(String name);

void removeAttribute(String name);

域对象(域对象就是在不同资源之前来共享数据,保存数据,获取数据)

ServletContext是我们学习的第一个域对象(Servlet共有三个域对象ServletContext、HttpServletRequest、HttpSession)

  1. 请求转发的

RequestDispatcher getRequestDispatcher(String path);

在Servlet跳转页面:

4.1请求重定向(你找我借钱,我没有,你自己去找他借钱)

1.地址栏会改变,变成重定向到的地址

2.可以跳转到项目内的资源,也可以跳转项目外的资源

3.浏览器向服务器发出两次请求,那么不能使用请求来作为域对象来共享数据。

4.2请求转发(你找我借钱,我没有,我帮你去向他借钱)

1.地址栏不会改变

2.只能跳转到项目内的资源,不能跳转项目外的资源。

3.浏览器向服务器发出一次请求,那么可以使用请求作为域对象共享数据。

5.读取web项目的资源文件

String getRealPath(String path);

InputStream getResourceAsStream(String path);

URL getResource(String path);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容