YiiWang

Spring Boot通过ApplicationContext来引用Service类
1.定义AppContextimport org.springframework.context.Applicat...
扫描右侧二维码阅读全文
30
2019/04

Spring Boot通过ApplicationContext来引用Service类

1.定义AppContext

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class AppContext implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
      private static ApplicationContext applicationContext;

      @Override
      public void setApplicationContext(ApplicationContext context) throws BeansException {
            applicationContext = context;
      }

      @SuppressWarnings("unchecked")
      public static <T> T getInstance(Class<?> clz) {
            Object obj = applicationContext.getBean(clz);
            if (obj == null) {
                  String clzName = clz.getSimpleName();
                  String first = String.valueOf(clzName.charAt(0));
                  clzName = first.toLowerCase() + clzName.substring(1);
                  obj = applicationContext.getBean(clzName);
            }
            return (T) obj;
      }

      @Override
      public void onApplicationEvent(ContextRefreshedEvent event) {
      }
}

2.在Application里面导入

@Import({AppContext.class})
@SpringBootApplication
public class AppApplication {
    …………
}

3.使用

 ServiceImpl serviceImpl = AppContext.getInstance(ServiceImpl.class);
 serviceImpl.doMethod();
Last modification:April 30th, 2019 at 02:17 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment