生成一个spring工具类 方便在非spring管理环境中获取bean,要求完整所有可能用到的接口
时间: 2024-05-05 20:16:40 浏览: 83
以下是一个可以在非spring管理环境中获取bean的工具类,包括了所有可能用到的接口:
```java
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return applicationContext.getBean(name, clazz);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<? extends Object> getType(String name) {
return applicationContext.getType(name);
}
public static String[] getAliases(String name) {
return applicationContext.getAliases(name);
}
}
```
使用方法:
在需要获取bean的地方,调用 `SpringContextUtil.getBean()` 方法即可。例如:
```java
UserService userService = SpringContextUtil.getBean(UserService.class);
```
阅读全文