Spring接口ApplicationContextAware介绍及使用

来源:互联网 发布:知乎的缺点 编辑:程序博客网 时间:2024/05/29 06:28

ApplicationContextAware接口的作用是将ApplicationContext设置到Bean中,这样我们写的Bean就能够获得他所在的应用程序上下文引用。通俗的说就是ApplicationContext容器中的Bean现在知道自己在哪个容器中了,有归属感了哈。这有什么作用呢?请看示例!(为了方便,我们使用普通的java项目)

1、需要引用的类

 

2、Bean类

package com.yayqi.bean;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public final class BeanLoader implements ApplicationContextAware{
 
 //保存应用程序上下文实例
 private static ApplicationContext ctx;
 
 private BeanLoader(){}
 
 //此处由Application容器自动注入
 @Override
 public void setApplicationContext(ApplicationContext arg0)
   throws BeansException {
  ctx = arg0;
  System.out.println("ApplicationContext 已经设置到BeanLoader中,你可以使用了!");
 }
 
 public static Object getBean(String beanName){
  return ctx.getBean(beanName);
 }
 
 public static <T> T getBean(String name, Class<T> c){
  return ctx.getBean(name, c);
 }
}


 
 public static <T> T getBean(String name, Class<T> c){
  return ctx.getBean(name, c);
 }
}

3、配置文件(注意红色部分)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jee="http://www.springframework.org/schema/jee"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd"
 default-lazy-init="true" default-autowire="byName">
 
 
 <bean id="user" class="com.yayqi.bean.User"></bean>
 
 <bean id="beanLoader" class="com.yayqi.bean.BeanLoader" lazy-init="false" ></bean>
 
</beans>

4、使用BeanLoader

public static void main(String[] args) throws Exception{
  
  //在web项目中Application是自动读取配置文件的
  ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
  User u = BeanLoader.getBean("user",User.class);
  System.out.println(u.toString());
 }

 

总结:我们可以在其他类使用BeanLoader类获得配置文件中的Bean,这样我们就不需要在配置文件中在给该类配置其引用的Bean(v ^ v)

0 0
原创粉丝点击