SpringUtil工具类
时间: 2023-05-23 14:05:23 浏览: 119
可以给出SpringUtil工具类的定义和使用方法吗?
A:SpringUtil是一个封装了Spring框架的ApplicationContext对象的工具类,提供了方便的获取bean的方法。可以通过以下方式定义SpringUtil:
```java
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringUtil.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(String name, Class<T> clazz) {
return applicationContext.getBean(name, clazz);
}
}
```
使用SpringUtil来获取bean可以分为三种情况:
1. 通过class获取bean
```java
UserService userService = SpringUtil.getBean(UserService.class);
```
2. 通过bean名称获取bean
```java
UserService userService = (UserService) SpringUtil.getBean("userService");
```
3. 通过class和bean名称获取bean
```java
UserService userService = SpringUtil.getBean("userService", UserService.class);
```
阅读全文