springcloud 注入 springcontextholder
时间: 2023-07-06 09:09:06 浏览: 105
可以使用`org.springframework.beans.factory.annotation.Autowired`注解将`org.springframework.context.ApplicationContext`注入到类中,然后使用`ApplicationContext`的`getBean()`方法获取需要的Bean对象,从而实现在Spring Cloud项目中使用`SpringContextHolder`。
示例代码如下:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class SpringContextHolder {
private static ApplicationContext applicationContext;
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}
```
在上述示例中,使用`@Autowired`注解将`ApplicationContext`注入到`SpringContextHolder`类中,然后在`getBean()`方法中使用`ApplicationContext`的`getBean()`方法获取需要的Bean对象。通过静态方法调用`SpringContextHolder.getBean()`即可获取Spring Bean对象。
阅读全文
相关推荐


















