spring的aware们

作者: 炫迈哥 | 来源:发表于2017-04-19 21:37 被阅读0次

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);

相关文章

  • spring的aware们

    Aware是什么 spring框架提供了多个*Aware接口,用于辅助Spring Bean编程访问Spring容...

  • Spring Aware容器感知技术

    ​ Spring Aware是什么 Spring提供Aware接口能让Bean感知Spring容器的存在,即让Be...

  • spring中Aware后缀

    aware: 意识到的;知道的; spring中带有Aware后缀的接口主要是和bean有关,实现了Aware后...

  • Spring高级应用 之Aware类

    1.Aware类为Bean感知Spring容器的存在提供支持,实现Aware类便可利用利用Spring容器中的各种...

  • SpringIoc之Aware

    Aware 概述 Aware是Spring提供的一个标记超接口,指示bean有资格通过回调样式的方法由Spring...

  • Aware Mode

    Aware接口 Spring中提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化之后,可以...

  • Spring Aware相关接口的使用

    在spring中提供了很多关于Aware的接口,该接口拥有一个统一的规律,即在spring对实现了Aware相关接...

  • Spring之Aware

    Aware Aware提供了一种让用户实现了Aware接口的自定义bean能够感知到被spring管理的资源的能力...

  • Spring AOP源码

    结合 Spring 后置处理器源码 和 Spring Aware源码 ,再来看下 Spring AOP 的源码。 ...

  • Spring Aware与静态方法的使用自动注入

    Spring Aware 1、介绍 Spring的依赖注入的最大亮点就是你所以的Bean对Spring容器的存在是...

网友评论

    本文标题:spring的aware们

    本文链接:https://www.haomeiwen.com/subject/rpwjnttx.html