美文网首页
根据用户传参生成Bean

根据用户传参生成Bean

作者: 胖达_4b7e | 来源:发表于2019-01-22 19:15 被阅读0次

    https://stackoverflow.com/questions/22155832/spring-java-config-how-do-you-create-a-prototype-scoped-bean-with-runtime-argu
    https://stackoverflow.com/questions/35108778/spring-bean-with-runtime-constructor-arguments

    工具类SpringContext

    @Component
    public class SpringContext implements ApplicationContextAware {
        private static ApplicationContext applicationContext;
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            SpringContext.applicationContext = applicationContext;
        }
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
        public static Object getBean(String name) {
            return getApplicationContext().getBean(name);
        }
    
        public static Object  getBean(String name,Object... args) {
            return getApplicationContext().getBean(name,args);
        }
    
        public static <T> T   getBean(Class<T> clazz,Object... args) {
            return getApplicationContext().getBean(clazz,args);
        }
    
        public static <T> T getBean(Class<T> clazz) {
            return getApplicationContext().getBean(clazz);
        }
        public static <T> T getBean(String name, Class<T> clazz) {
            return getApplicationContext().getBean(name, clazz);
        }
    }
    

    1.配置工厂

    @Configuration
    public class XXXConfig {
    
        @Bean
        @Scope(value = "prototype")
        @Lazy
        public  XXXService xxService(PlatformAccount[] accounts) {
         
        }
    
    

    使用 platformAccount是用户选择的传参

      XXXService service  =  (XXXService ) SpringContext.getBean("xxService",new PlatformAccount[]{platformAccount});
    

    2.如果XXXService 就一个实现,

    @Service
    @Lazy
    @Scope(value = "prototype")
    public class XXXService {
      public XXXService ( 构造方法传参) {
          
        }
    }
    

    可以用类直接得到

    SpringContext.getBean(XXXService .class, 构造方法的参数);
    

    相关文章

      网友评论

          本文标题:根据用户传参生成Bean

          本文链接:https://www.haomeiwen.com/subject/trurjqtx.html