spring中通过ApplicationContext getBean获取注入对象的方法实例

网友投稿 650 2023-01-10


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, LooFcfRsmMcale.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类

总结

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微服务网关详解(微服务 api网关)
下一篇:微服务网关限流算法(微服务网关集群)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~