多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
ApplicationContextAware 接口可以获取 IoC 上下文,从而获取注册到 IoC 容器里面的组件。 <br/> **1. 实现接口 ApplicationContextAware** ```java @Component public class ApplicationContextUtils implements ApplicationContextAware { private static ApplicationContext context; public static <T> T getBean(Class<T> requiredType) { return context.getBean(requiredType); } public static <T> T getBean(String name, Class<T> requiredType) { return context.getBean(name, requiredType); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } } ``` <br/> **2. 有一个注册到 IoC 容器的组件** ```java @Service public class UserServiceImpl implements UserService { @Override public String findUsername(Integer id) { return "[findUsername|id]: " + id; } } ``` <br/> **3. 测试** ```java @SpringBootTest class ComptsApplicationTests { @Test void contextLoads() { //获取UserServiceImpl UserService userService = ApplicationContextUtils.getBean(UserServiceImpl.class); System.out.println(userService.findUsername(100)); ///[findUsername|id]: 100 } } ``` **** 案例代码:https://gitee.com/flymini/codes03/tree/master/learn-bootcompts