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类

 
     
     
     
     
      
      
      
  
  
    
    
    
    
    
    
  

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

你可能感兴趣的:(spring中通过ApplicationContext getBean获取注入对象的方法实例)