一、通过@Autowired和@Resource的方式获取bean。
例如:
@Resource
private ApplicationContext applicationContext;
@Autowired
private ApplicationContext applicationContext;
此例子是活的了applicationContext容器。
二、通过ApplicationContext.getBean()方法获得bean
例如:
CodeTest test = applicationContext.getBean(CodeTest.class);
CodeTest类上要加上Services,Compent等注解,如果在注解里取了其他名字,例如Component("test")
获取如下:
CodeTest initCodec = applicationContext.getBean("test", CodeTest .class);
那如果在某个类中无法使用注解,该如何获取到bean呢?接下来 有两种方式,其中第一种 最为简单。
一、使用类中静态属性,并配合@Autowired和@Resource
例如:
@Component
public class TestUtil {
private static StringRedisTemplate stringRedisTemplate;
@Autowired
public TestUtil (StringRedisTemplate stringRedisTemplate){
MqttSessionUtil.stringRedisTemplate = stringRedisTemplate;
}
public static void setRedisHashKey(String h, String k, String v) {
stringRedisTemplate.opsForHash().put(h, k, v);
}
public static Object getRedisHashkey(String h, String k) {
return stringRedisTemplate.opsForHash().get(h, k);
}
}
外部调用,只需要调用封装方法就行。注意事项时一定要在类上标注Component
二、参考我的另一篇博文:https://blog.csdn.net/qq_34239851/article/details/88234328