第一种:SpringUtil
@Component
public class SpringUtil extends ApplicationObjectSupport {
public static ApplicationContext context;
public static Object getBean(String serviceName){
return context.getBean(serviceName);
}
@Override
protected void initApplicationContext(ApplicationContext context) throws BeansException {
super.initApplicationContext(context);
SpringUtil.context = context;
}
}
ApplicationContext context = SpringUtil.context;
PayServiceUtil payServiceUtil = context.getBean(PayServiceUtil.class);
Map<String, PayService> payMap = context.getBeansOfType(PayService.class);
第二种:PayServiceUtil
@Component
public class PayServiceUtil implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
Map<String, PayService> payMap = applicationContext.getBeansOfType(PayService.class);
第三种AppConfig方法
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
DeptMapperImpl deptMapper = context.getBean(DeptMapperImpl.class);
deptMapper.test();
}
}
@ComponentScan("com.base")
@Configuration
public class AppConfig {
}
第四种NonAppConfig方法(第三种合二为一)
@ComponentScan("com")
public class TestNoAppConfig {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainApplication.class);
DeptService deptService = context.getBean(DeptService.class);
deptService.delete(new Dept());
}
}
第五种 启动类
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
}
}