private void initWildcardDefinitionMap() { if (null != appContexts) { for (ApplicationContext appContext : appContexts) { for (String n : appContext.getBeanDefinitionNames()) { if (isWildcardBeanName(n)) { AutowireCapableBeanFactory bf = appContext.getAutowireCapableBeanFactory(); BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) bf; BeanDefinition bd = bdr.getBeanDefinition(n); String className = bd.getBeanClassName(); if (null != className) { String orig = n; if (n.charAt(0) == '*') { // old wildcard n = "." + n.replaceAll("\\.", "\\."); } try { Matcher matcher = Pattern.compile(n).matcher(""); List<MatcherHolder> m = wildCardBeanDefinitions.get(className); if (m == null) { m = new ArrayList<MatcherHolder>(); wildCardBeanDefinitions.put(className, m); } MatcherHolder holder = new MatcherHolder(orig, matcher); m.add(holder); } catch (PatternSyntaxException npe) { // not a valid patter, we'll ignore } } else { LOG.warn("Wildcars with not class {}", n); } } } } } }
private String getResourceDescription(String beanName, ListableBeanFactory beanFactory) { if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; return registry.getBeanDefinition(beanName).getResourceDescription(); } return "unknown"; }
/** * Registers bean definitions for a {@link PluginRegistry} to capture {@link RelProvider} * instances. Wraps the registry into a {@link DelegatingRelProvider} bean definition backed by * the registry. * * @param registry */ private static void registerRelProviderPluginRegistryAndDelegate( BeanDefinitionRegistry registry) { Class<?> defaultRelProviderType = EVO_PRESENT ? EvoInflectorRelProvider.class : DefaultRelProvider.class; RootBeanDefinition defaultRelProviderBeanDefinition = new RootBeanDefinition(defaultRelProviderType); registry.registerBeanDefinition("defaultRelProvider", defaultRelProviderBeanDefinition); RootBeanDefinition annotationRelProviderBeanDefinition = new RootBeanDefinition(AnnotationRelProvider.class); registry.registerBeanDefinition("annotationRelProvider", annotationRelProviderBeanDefinition); BeanDefinitionBuilder registryFactoryBeanBuilder = BeanDefinitionBuilder.rootBeanDefinition(PluginRegistryFactoryBean.class); registryFactoryBeanBuilder.addPropertyValue("type", RelProvider.class); registryFactoryBeanBuilder.addPropertyValue("exclusions", DelegatingRelProvider.class); AbstractBeanDefinition registryBeanDefinition = registryFactoryBeanBuilder.getBeanDefinition(); registry.registerBeanDefinition("relProviderPluginRegistry", registryBeanDefinition); BeanDefinitionBuilder delegateBuilder = BeanDefinitionBuilder.rootBeanDefinition(DelegatingRelProvider.class); delegateBuilder.addConstructorArgValue(registryBeanDefinition); AbstractBeanDefinition beanDefinition = delegateBuilder.getBeanDefinition(); beanDefinition.setPrimary(true); registry.registerBeanDefinition(DELEGATING_REL_PROVIDER_BEAN_NAME, beanDefinition); }
private void registerBeanDefinitionsWithRegistry(BeanDefinitionRegistry registry) { for (Object key : beanDefinitions.keySet()) { BeanDefinition bd = beanDefinitions.get(key); if (LOG.isDebugEnabled()) { LOG.debug("[RuntimeConfiguration] Registering bean [" + key + "]"); if (LOG.isTraceEnabled()) { PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues(); for (PropertyValue pv : pvs) { LOG.trace( "[RuntimeConfiguration] With property [" + pv.getName() + "] set to [" + pv.getValue() + "]"); } } } final String beanName = key.toString(); if (registry.containsBeanDefinition(beanName)) { removeBeanDefinition(registry, beanName); } registry.registerBeanDefinition(beanName, bd); registerBeanAliases(registry, beanName); } }
@Override public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) { Map<String, Object> attrs = meta.getAnnotationAttributes(EnableReactor.class.getName()); // Create a root Enivronment if (!registry.containsBeanDefinition(Environment.class.getName())) { BeanDefinitionBuilder envBeanDef = BeanDefinitionBuilder.rootBeanDefinition(Environment.class); String configReaderBean = (String) attrs.get("configurationReader"); if (StringUtils.hasText(configReaderBean)) { envBeanDef.addConstructorArgReference(configReaderBean); } else { String profileName = (String) attrs.get("value"); if (StringUtils.hasText(profileName)) { envBeanDef.addConstructorArgValue(new PropertiesConfigurationReader(profileName)); } } registry.registerBeanDefinition(Environment.class.getName(), envBeanDef.getBeanDefinition()); } // Create a ConsumerBeanPostProcessor if (!registry.containsBeanDefinition(ConsumerBeanPostProcessor.class.getName())) { BeanDefinitionBuilder envBeanDef = BeanDefinitionBuilder.rootBeanDefinition(ConsumerBeanPostProcessor.class); registry.registerBeanDefinition( ConsumerBeanPostProcessor.class.getName(), envBeanDef.getBeanDefinition()); } }
@Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Collection<Class<?>> remotingServices = new HashSet<Class<?>>(); remotingServices.addAll(getIncludeClasses()); String[] basePackages = getBasePackages(); if (basePackages != null) remotingServices.addAll(ClassScanner.scanAnnotated(basePackages, Remoting.class)); Collection<Class<?>> excludeRemotingServices = getExcludeClasses(); for (Class<?> remotingService : remotingServices) { if (!remotingService.isInterface() || excludeRemotingServices.contains(remotingService)) continue; String beanName = StringUtils.uncapitalize(remotingService.getSimpleName()); if (registry.containsBeanDefinition(beanName)) { logger.info( "Skip bean {} which implemented by {}", beanName, registry.getBeanDefinition(beanName).getBeanClassName()); continue; } RootBeanDefinition beanDefinition = new RootBeanDefinition(HttpInvokerClient.class); beanDefinition.setTargetType(remotingService); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("serviceInterface", remotingService.getName()); beanDefinition.setPropertyValues(propertyValues); registry.registerBeanDefinition(beanName, beanDefinition); logger.info("Registered bean {} for remoting service", beanName); } }
/** * Register a {@link WebSocketHandlerMappingFactoryBean} which could also be overridden by the * user by simply using {@link org.springframework.web.socket.config.annotation.EnableWebSocket} * * <p>In addition, checks if the {@code javax.servlet.Servlet} class is present on the classpath. * When Spring Integration WebSocket support is used only as a WebSocket client, there is no * reason to use and register the Spring WebSocket server components. * * <p>Note, there is no XML equivalent for the {@link * org.springframework.web.socket.config.annotation .EnableWebSocket} in the Spring WebSocket. * therefore this registration can be used to process {@link WebSocketConfigurer} implementations * without annotation configuration. From other side it can be used to replace {@link * org.springframework.web.socket.config.annotation.EnableWebSocket} in the Spring Integration * applications when {@link org.springframework.integration.config.EnableIntegration} is in use. */ private void registerEnableWebSocketIfNecessary(BeanDefinitionRegistry registry) { if (servletPresent) { if (!registry.containsBeanDefinition("defaultSockJsTaskScheduler")) { BeanDefinitionBuilder sockJsTaskSchedulerBuilder = BeanDefinitionBuilder.genericBeanDefinition(ThreadPoolTaskScheduler.class) .addPropertyValue("threadNamePrefix", "SockJS-") .addPropertyValue("poolSize", Runtime.getRuntime().availableProcessors()) .addPropertyValue("removeOnCancelPolicy", true); registry.registerBeanDefinition( "defaultSockJsTaskScheduler", sockJsTaskSchedulerBuilder.getBeanDefinition()); } if (!registry.containsBeanDefinition(DelegatingWebSocketConfiguration.class.getName()) && !registry.containsBeanDefinition(WEB_SOCKET_HANDLER_MAPPING_BEAN_NAME)) { BeanDefinitionBuilder enableWebSocketBuilder = BeanDefinitionBuilder.genericBeanDefinition(WebSocketHandlerMappingFactoryBean.class) .setRole(BeanDefinition.ROLE_INFRASTRUCTURE) .addConstructorArgReference("defaultSockJsTaskScheduler"); registry.registerBeanDefinition( WEB_SOCKET_HANDLER_MAPPING_BEAN_NAME, enableWebSocketBuilder.getBeanDefinition()); } } }
private void registerBeanConfigsWithRegistry(BeanDefinitionRegistry registry) { for (BeanConfiguration bc : beanConfigs.values()) { String beanName = bc.getName(); if (LOG.isDebugEnabled()) { LOG.debug("[RuntimeConfiguration] Registering bean [" + beanName + "]"); if (LOG.isTraceEnabled()) { PropertyValue[] pvs = bc.getBeanDefinition().getPropertyValues().getPropertyValues(); for (PropertyValue pv : pvs) { LOG.trace( "[RuntimeConfiguration] With property [" + pv.getName() + "] set to [" + pv.getValue() + "]"); } } } if (registry.containsBeanDefinition(beanName)) { removeBeanDefinition(registry, beanName); } registry.registerBeanDefinition(beanName, bc.getBeanDefinition()); registerBeanAliases(registry, beanName); } }
public BeanDefinition parse(Element element, ParserContext parserContext) { final XmlReaderContext readerContext = parserContext.getReaderContext(); final ClassLoader beanClassLoader = readerContext.getBeanClassLoader() != null ? readerContext.getBeanClassLoader() : Thread.currentThread().getContextClassLoader(); String[] basePackages = StringUtils.commaDelimitedListToStringArray(element.getAttribute(BASE_PACKAGE_ATTRIBUTE)); String dataSourceId = element.getAttribute(DATA_SOURCE_ATTRIBUTE); if (!StringUtils.hasText(dataSourceId)) { throw new BeanDefinitionParsingException( new Problem( "Attribute [" + DATA_SOURCE_ATTRIBUTE + "] of tag <gorm:sessionFactory> must be specified!", new Location(readerContext.getResource()))); } // Actually scan for bean definitions and register them. BeanDefinitionRegistry targetRegistry = parserContext.getRegistry(); // setup the GrailsApplication instance parseGrailsApplication(element, parserContext, readerContext, beanClassLoader, basePackages); GenericBeanDefinition postProccessingBeanDef = new GenericBeanDefinition(); postProccessingBeanDef.setBeanClass(GORMEnhancingBeanPostProcessor.class); targetRegistry.registerBeanDefinition("gormEnhancingPostProcessor", postProccessingBeanDef); return parseSessionFactory(element, dataSourceId, targetRegistry, parserContext); }
@Override public BeanDefinition parse(Element element, ParserContext parserContext) { Object source = parserContext.extractSource(element); CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source); parserContext.pushContainingComponent(compDefinition); BeanDefinitionRegistry registry = parserContext.getRegistry(); if (registry.containsBeanDefinition(STAT_ANNOTATION_PROCESSOR_BEAN_NAME)) { parserContext .getReaderContext() .error("Only one DruidStatBeanDefinitionParser may exist within the context.", source); } else { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(STAT_ANNOTATION_PROCESSOR_BEAN_CLASS); builder.getRawBeanDefinition().setSource(source); registerComponent(parserContext, builder, STAT_ANNOTATION_PROCESSOR_BEAN_NAME); } if (!registry.containsBeanDefinition(STAT_ANNOTATION_ADVICE_BEAN_NAME)) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(STAT_ANNOTATION_ADVICE_BEAN_CLASS); builder.getRawBeanDefinition().setSource(source); registerComponent(parserContext, builder, STAT_ANNOTATION_ADVICE_BEAN_NAME); } parserContext.popAndRegisterContainingComponent(); return null; }
private AbstractBeanDefinition parseSessionFactory( Element element, String dataSourceId, BeanDefinitionRegistry targetRegistry, ParserContext parserContext) { String sessionFactoryId = StringUtils.hasText(element.getAttribute(ID_ATTRIBUTE)) ? element.getAttribute(ID_ATTRIBUTE) : "sessionFactory"; AbstractBeanDefinition sessionFactoryBean = new GenericBeanDefinition(); sessionFactoryBean.setBeanClass(ConfigurableLocalSessionFactoryBean.class); MutablePropertyValues propertyValues = sessionFactoryBean.getPropertyValues(); final RuntimeBeanReference dataSourceRef = new RuntimeBeanReference(dataSourceId); propertyValues.addPropertyValue("dataSource", dataSourceRef); Class<?> configClass = lookupConfigClass(element, parserContext); propertyValues.addPropertyValue("configClass", configClass); final String configLocation = element.getAttribute(CONFIG_LOCATION_ATTRIBUTE); if (StringUtils.hasText(configLocation)) { propertyValues.addPropertyValue("configLocation", configLocation); } propertyValues.addPropertyValue( GrailsApplication.APPLICATION_ID, new RuntimeBeanReference(GrailsApplication.APPLICATION_ID)); targetRegistry.registerBeanDefinition(sessionFactoryId, sessionFactoryBean); final String lobHandlerRef = element.getAttribute(LOB_HANDLER_ATTRIBUTE); if (StringUtils.hasText(lobHandlerRef)) { propertyValues.addPropertyValue("lobHandler", new RuntimeBeanReference(lobHandlerRef)); } else { GenericBeanDefinition lobHandler = new GenericBeanDefinition(); lobHandler.setBeanClass(SpringLobHandlerDetectorFactoryBean.class); lobHandler.getPropertyValues().addPropertyValue("pooledConnection", true); lobHandler.getPropertyValues().addPropertyValue("dataSource", dataSourceRef); propertyValues.addPropertyValue("lobHandler", lobHandler); } String transactionManagerRef = element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE); if (StringUtils.hasText(transactionManagerRef)) { targetRegistry.registerAlias(transactionManagerRef, "transactionManager"); } else { GenericBeanDefinition transactionManagerBean = new GenericBeanDefinition(); transactionManagerBean.setBeanClass(GrailsHibernateTransactionManager.class); transactionManagerBean .getPropertyValues() .addPropertyValue("sessionFactory", new RuntimeBeanReference(sessionFactoryId)); targetRegistry.registerBeanDefinition("transactionManager", transactionManagerBean); } parserContext.getDelegate().parsePropertyElements(element, sessionFactoryBean); return sessionFactoryBean; }
/** * Registers the given {@link AbstractBeanDefinition} with the given registry with the given bean * name unless the registry already contains a bean with that name. * * @param bean must not be {@literal null}. * @param registry must not be {@literal null}. * @param beanName must not be {@literal null} or empty. * @param source must not be {@literal null}. */ public static void registerIfNotAlreadyRegistered( AbstractBeanDefinition bean, BeanDefinitionRegistry registry, String beanName, Object source) { if (registry.containsBeanDefinition(beanName)) { return; } bean.setSource(source); registry.registerBeanDefinition(beanName, bean); }
@Override public synchronized <T> T registerAndGetBean( Class<? extends T> type, final String id, final Scope scope) { if (contains(id)) return getBean(id); final AutowireCapableBeanFactory factory = getContext().getAutowireCapableBeanFactory(); final BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory; final GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(type); if (scope != null) beanDefinition.setScope(scope.getType()); beanDefinition.setAutowireCandidate(true); registry.registerBeanDefinition(id, beanDefinition); factory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); return getBean(id); }
@Override protected void createOperationsBean(BeanDefinitionRegistry registry) { String beanName = "s3ResourceTemplate"; BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(S3ResourceTemplate.class); registry.registerBeanDefinition(beanName, builder.getBeanDefinition()); }
private void registerUnrefreshedBeansWithRegistry(BeanDefinitionRegistry registry) { if (context != null) { for (String beanName : context.getBeanDefinitionNames()) { registry.registerBeanDefinition(beanName, context.getBeanDefinition(beanName)); } } }
private void registerBeanAliases(BeanDefinitionRegistry beanDefinitionRegistry, String beanName) { List<String> beanAliases = aliases.get(beanName); if (beanAliases != null && !beanAliases.isEmpty()) { for (String alias : beanAliases) { beanDefinitionRegistry.registerAlias(beanName, alias); } } }
private void process( BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory) { BeanDefinitionHolder holder = getDataSourceBeanDefinition(beanFactory); if (holder != null) { logger.info( "Replacing '" + holder.getBeanName() + "' DataSource bean with embedded version"); registry.registerBeanDefinition(holder.getBeanName(), createEmbeddedBeanDefinition()); } }
/** * Register the specified entity scan packages with the system. * * @param registry the source registry * @param packageNames the package names to register */ public static void register(BeanDefinitionRegistry registry, Collection<String> packageNames) { Assert.notNull(registry, "Registry must not be null"); Assert.notNull(packageNames, "PackageNames must not be null"); if (registry.containsBeanDefinition(BEAN)) { BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN); ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); constructorArguments.addIndexedArgumentValue( 0, addPackageNames(constructorArguments, packageNames)); } else { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(EntityScanPackages.class); beanDefinition .getConstructorArgumentValues() .addIndexedArgumentValue(0, packageNames.toArray(new String[packageNames.size()])); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN, beanDefinition); } }
/** * Sets the given source on the given {@link AbstractBeanDefinition} and registers it inside the * given {@link BeanDefinitionRegistry}. For {@link BeanDefinition}s to be registerd * once-and-only-once for all configuration elements (annotation or XML), prefer calling {@link * #registerIfNotAlreadyRegistered(AbstractBeanDefinition, BeanDefinitionRegistry, String, * Object)} with a dedicated bean name to avoid the bead definition being registered multiple * times. * * * @param registry must not be {@literal null}. * @param bean must not be {@literal null}. * @param source must not be {@literal null}. * @return the bean name generated for the given {@link BeanDefinition} */ public static String registerWithSourceAndGeneratedBeanName( BeanDefinitionRegistry registry, AbstractBeanDefinition bean, Object source) { bean.setSource(source); String beanName = generateBeanName(bean, registry); registry.registerBeanDefinition(beanName, bean); return beanName; }
@Override protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Assert.notEmpty(basePackages, "At least one base package must be specified"); Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>(); for (String basePackage : basePackages) { Set<BeanDefinition> candidates = findCandidateComponents(basePackage); for (BeanDefinition candidate : candidates) { ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate); candidate.setScope(scopeMetadata.getScopeName()); String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry); if (candidate instanceof AbstractBeanDefinition) { postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName); } if (candidate instanceof AnnotatedBeanDefinition) { processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate); } ScannedGenericBeanDefinition bd = (ScannedGenericBeanDefinition) candidate; // 通用bean扫描 bd.setBeanClassName(HessianServiceExporter.class.getName()); // 设置bean名称 bd.setBeanClass(HessianServiceExporter.class); // 设置bean类 bd.getPropertyValues().add("service", registry.getBeanDefinition(beanName)); // 设置属性 service String[] interfaces = bd.getMetadata().getInterfaceNames(); // 获得元数据、接口名称 if (interfaces == null || interfaces.length == 0) continue; Class interf = null; try { interf = Class.forName(interfaces[0]); // 获得接口 } catch (ClassNotFoundException e) { continue; } bd.getPropertyValues().add("serviceInterface", interf); // 设置属性 serviceInterface candidate = bd; BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, "/" + beanName); // 新bean定义持有 definitionHolder = applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); // 应用范围代理模式 beanDefinitions.add(definitionHolder); // 将bean定义持有放入bean定义持有set中 registerBeanDefinition(definitionHolder, this.registry); // 注册bean定义 } } if (beanDefinitions.isEmpty()) { System.out.println("not service be scaned"); } else { for (BeanDefinitionHolder holder : beanDefinitions) { AnnotatedBeanDefinition definition = (AnnotatedBeanDefinition) holder.getBeanDefinition(); // 注释的bean定义 System.out.println("service:" + holder.getBeanName()); // 注释的bean定义名称 System.out.println( "service:" + definition.getMetadata().getAnnotationTypes()); // 注释的bean定义类型 } } return beanDefinitions; }
private void processRegularClass(BeanDefinitionRegistry registry, Class implementation) { LOG.debug( String.format( "Registering bean definition for implementation class %s", implementation.getCanonicalName())); String beanName = implementation.getCanonicalName(); GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(implementation); beanDefinition.setAutowireMode(AUTOWIRE_BY_TYPE); registry.registerBeanDefinition(beanName, beanDefinition); }
private void parseGrailsApplication( Element element, ParserContext parserContext, XmlReaderContext readerContext, ClassLoader beanClassLoader, String[] basePackages) { BeanDefinitionRegistry simpleRegistry = new SimpleBeanDefinitionRegistry(); ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, simpleRegistry); scanner.scan(basePackages); BeanDefinitionRegistry targetRegistry = parserContext.getRegistry(); AbstractBeanDefinition grailsApplicationBean = new GenericBeanDefinition(); grailsApplicationBean.setBeanClass(DefaultGrailsApplication.class); grailsApplicationBean.setInitMethodName("initialise"); ConstructorArgumentValues constructorArgs = grailsApplicationBean.getConstructorArgumentValues(); Set<Class<?>> classes = new HashSet<Class<?>>(); for (String beanName : simpleRegistry.getBeanDefinitionNames()) { BeanDefinition beanDef = simpleRegistry.getBeanDefinition(beanName); try { Class<?> entityClass = Class.forName(beanDef.getBeanClassName(), true, beanClassLoader); classes.add(entityClass); registerDomainBean( entityClass, targetRegistry, element.getAttribute(MESSAGE_SOURCE_ATTRIBUTE)); } catch (ClassNotFoundException e) { throw new BeanDefinitionParsingException( new Problem( "Unable to load class whilst configuring GORM: " + e.getMessage(), new Location(readerContext.getResource()), null, e)); } } constructorArgs.addGenericArgumentValue(classes.toArray(new Class[classes.size()])); constructorArgs.addGenericArgumentValue(beanClassLoader); targetRegistry.registerBeanDefinition(GrailsApplication.APPLICATION_ID, grailsApplicationBean); }
@Override public void registerBeanDefinitions( AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { if (this.beanFactory != null && this.beanFactory .getBeansOfType(EmbeddedServletContainerCustomizerBeanPostProcessor.class) .size() == 0) { BeanDefinition beanDefinition = new RootBeanDefinition(EmbeddedServletContainerCustomizerBeanPostProcessor.class); registry.registerBeanDefinition( "embeddedServletContainerCustomizerBeanPostProcessor", beanDefinition); } }
private void processRepositoryInterface( BeanDefinitionRegistry registry, Class repositoryInterface) { LOG.debug( String.format( "Registering bean definition for repository interface %s", repositoryInterface.getCanonicalName())); String beanName = Introspector.decapitalize(repositoryInterface.getSimpleName()); GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(JpaRepositoryFactoryBean.class); MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(); mutablePropertyValues.add("repositoryInterface", repositoryInterface); beanDefinition.setPropertyValues(mutablePropertyValues); registry.registerBeanDefinition(beanName, beanDefinition); }
/** * 增加自动跟踪的auto tracer bean definition * * @param beanFactory */ public static void addTracerBeanDefinition(final BeanDefinitionRegistry beanFactory) { AbstractBeanDefinition pointcut = new GenericBeanDefinition(); pointcut.setBeanClassName( org.jtester.module.tracer.spring.TracerMethodRegexPointcut.class.getName()); pointcut.setScope("singleton"); pointcut.setAutowireCandidate(false); pointcut.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_NO); beanFactory.registerBeanDefinition("jtester-internal-methodname-pointcut", pointcut); AbstractBeanDefinition advice = new GenericBeanDefinition(); advice.setBeanClassName(org.jtester.module.tracer.spring.SpringBeanTracer.class.getName()); advice.setScope("singleton"); advice.setAutowireCandidate(false); advice.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_NO); beanFactory.registerBeanDefinition("jtester-internal-springbeantracer", advice); AbstractBeanDefinition advisor = new GenericBeanDefinition(); advisor.setBeanClassName( org.springframework.aop.support.DefaultPointcutAdvisor.class.getName()); advisor.setScope("singleton"); advisor.setAutowireCandidate(false); advisor.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_NO); advisor .getPropertyValues() .addPropertyValue( "pointcut", new RuntimeBeanReference("jtester-internal-methodname-pointcut")); advisor .getPropertyValues() .addPropertyValue("advice", new RuntimeBeanReference("jtester-internal-springbeantracer")); beanFactory.registerBeanDefinition("jtester-internal-beantracer-advisor", advisor); }
@Override public Object buildBean(String beanName, Map<String, Object> extraContext) throws Exception { LOG.debug("Building bean for name {}", beanName); if (!skipBeanNames.contains(beanName)) { ApplicationContext anAppContext = getApplicationContext(extraContext); try { LOG.debug( "Trying the application context... appContext = {},\n bean name = {}", anAppContext, beanName); return anAppContext.getBean(beanName); } catch (NoSuchBeanDefinitionException e) { LOG.debug( "Did not find bean definition for bean named {}, creating a new one...", beanName); if (autoWiringFactory instanceof BeanDefinitionRegistry) { try { Class clazz = Class.forName(beanName); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) autoWiringFactory; RootBeanDefinition def = new RootBeanDefinition(clazz, autowireStrategy, true); def.setScope(BeanDefinition.SCOPE_SINGLETON); LOG.debug("Registering a new bean definition for class {}", beanName); registry.registerBeanDefinition(beanName, def); try { return anAppContext.getBean(beanName); } catch (NoSuchBeanDefinitionException e2) { LOG.warn("Could not register new bean definition for bean {}", beanName); skipBeanNames.add(beanName); } } catch (ClassNotFoundException e1) { skipBeanNames.add(beanName); } } } } LOG.debug("Returning autowired instance created by default ObjectFactory"); return autoWireBean(super.buildBean(beanName, extraContext), autoWiringFactory); }
private void registerDomainBean( final Class<?> entityClass, BeanDefinitionRegistry targetRegistry, String messageSourceRef) { GenericBeanDefinition beanDef = new GenericBeanDefinition(); beanDef.setBeanClass(entityClass); beanDef.setScope("prototype"); RootBeanDefinition domainDef = new RootBeanDefinition(MethodInvokingFactoryBean.class); domainDef .getPropertyValues() .addPropertyValue( "targetObject", new RuntimeBeanReference(GrailsApplication.APPLICATION_ID)); domainDef.getPropertyValues().addPropertyValue("targetMethod", "getArtefact"); domainDef .getPropertyValues() .addPropertyValue( "arguments", Arrays.asList(DomainClassArtefactHandler.TYPE, entityClass.getName())); final String domainRef = entityClass.getName() + "Domain"; if (StringUtils.hasText(messageSourceRef)) { GenericBeanDefinition validatorDef = new GenericBeanDefinition(); validatorDef.setBeanClass(HibernateDomainClassValidator.class); validatorDef .getPropertyValues() .addPropertyValue("messageSource", new RuntimeBeanReference(messageSourceRef)); validatorDef .getPropertyValues() .addPropertyValue("domainClass", new RuntimeBeanReference(domainRef)); validatorDef .getPropertyValues() .addPropertyValue("sessionFactory", new RuntimeBeanReference("sessionFactory")); targetRegistry.registerBeanDefinition(entityClass.getName() + "Validator", validatorDef); } targetRegistry.registerBeanDefinition(entityClass.getName(), beanDef); targetRegistry.registerBeanDefinition(domainRef, domainDef); }
/** * Returns the bean name of a {@link MappingContext} to be wired. Will inspect the namespace * attribute first and if no config is found in that place it will try to lookup the default one. * Will return {@literal null} if neither one is available. * * @param config * @param registry * @return */ private String getMappingContextReference( MongoRepositoryConfiguration config, BeanDefinitionRegistry registry) { String contextRef = config.getMappingContextRef(); if (contextRef != null) { return contextRef; } try { registry.getBeanDefinition(MAPPING_CONTEXT_DEFAULT); return MAPPING_CONTEXT_DEFAULT; } catch (NoSuchBeanDefinitionException e) { return null; } }
private void testBeanDefinitions(BeanDefinitionRegistry registry) { assertEquals(24, registry.getBeanDefinitionCount()); assertEquals(24, registry.getBeanDefinitionNames().length); assertTrue(Arrays.asList(registry.getBeanDefinitionNames()).contains("rod")); assertTrue(Arrays.asList(registry.getBeanDefinitionNames()).contains("aliased")); assertTrue(registry.containsBeanDefinition("rod")); assertTrue(registry.containsBeanDefinition("aliased")); assertEquals(TestBean.class.getName(), registry.getBeanDefinition("rod").getBeanClassName()); assertEquals( TestBean.class.getName(), registry.getBeanDefinition("aliased").getBeanClassName()); assertTrue(registry.isAlias("youralias")); assertEquals(2, registry.getAliases("aliased").length); assertEquals("myalias", registry.getAliases("aliased")[0]); assertEquals("youralias", registry.getAliases("aliased")[1]); }
/** * Returns whether the given {@link BeanDefinitionRegistry} already contains a bean of the given * type assuming the bean name has been autogenerated. * * @param type * @param registry * @return */ public static boolean hasBean(Class<?> type, BeanDefinitionRegistry registry) { String name = String.format("%s%s0", type.getName(), GENERATED_BEAN_NAME_SEPARATOR); return registry.containsBeanDefinition(name); }