spring 中通过ApplicationContext getBean获取注入对象

用SpringContextUtil实现 ApplicationContextAware
package util;

import java.util.Locale;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil
  implements ApplicationContextAware
{
  private static ApplicationContext context;

  @Override
  public void setApplicationContext(ApplicationContext contex)
    throws BeansException
  {
	  System.out.println("--------------------contex---------"+contex);
	  SpringContextUtil.context = contex;
  }
  
  
  public static ApplicationContext getApplicationContext() { 
      return context; 
  } 
  
  public static Object getBean(String beanName) {
    return context.getBean(beanName);
  }

  public static String getMessage(String key) {
    return context.getMessage(key, null, Locale.getDefault());
  }
}
工具类
package redis;

import redis.clients.jedis.JedisPool;
import util.SpringContextUtil;

public class RedisUtil {

	
	 private static JedisPool jedisPool;
	 
	 static{
		 jedisPool = (JedisPool)SpringContextUtil.getBean("jedisPool"); 
	 }
	  
	  public static JedisPool getJedisPool(){
		  if(jedisPool == null){
			  jedisPool = (JedisPool)SpringContextUtil.getBean("jedisPool"); 
		  }
		  return jedisPool;
	  }
	  
	  public void flusDB(){
		  jedisPool.getResource().flushDB();
	  }
	  
	  
	  public static String set(String key,String value){
		  return jedisPool.getResource().set(key, value);
	  }
	  
	  public static String get(String key){
		  return jedisPool.getResource().get(key);
	  }
	
	  
	  public static Long del(String key){
		  return jedisPool.getResource().del(key);
	  }
	  
}
在Spring的配置文件中配置这个类,Spring容器会在加载完Spring容器后把上下文对象调用这个对象中的setApplicationContext方法
  
   
  
    
    
    
    	
    		classpath:jdbc.properties
    		classpath:redis.properties
    	
    
   
  
  
  
在web项目中的web.xml中配置加载Spring容器的Listener
 
 
	org.springframework.web.context.ContextLoaderListener 
spring配置文件注入Bean类
  
         
         
        
          
         
           
            
            
    
    
    
        
        
        
        
        
        
    




你可能感兴趣的:(JAVA)