用 ApplicationContextAware 实现一个springboot的工厂类
时间: 2023-12-29 15:26:13 浏览: 26
使用ApplicationContextAware接口可以实现在Spring Boot中使用工厂类。下面是一个示例:
```java
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class MyFactory implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
MyFactory.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return applicationContext.getBean(beanClass);
}
}
```
在上面的示例中,我们创建了一个名为MyFactory的类,并实现了ApplicationContextAware接口。通过实现setApplicationContext方法,我们可以获取到Spring的ApplicationContext对象,并将其保存在静态变量中。
然后,我们可以使用getBean方法来获取其他的Bean实例。例如,如果我们想要获取一个名为CarService的Bean实例,可以使用以下代码:
```java
CarService carService = MyFactory.getBean(CarService.class);
```
这样,我们就可以在Spring Boot中使用ApplicationContextAware接口实现一个工厂类。