Java Code Examples for org.springframework.context.annotation.ClassPathBeanDefinitionScanner

The following examples show how to use org.springframework.context.annotation.ClassPathBeanDefinitionScanner. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: joyrpc   Source File: RpcDefinitionPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 处理rpc扫描的包下的class类
 *
 * @param packages 包集合
 * @param registry 注册中心
 */
protected void processPackages(Set<String> packages, BeanDefinitionRegistry registry) {
    //构造
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false, environment, resourceLoader);
    registerAnnotationConfigProcessors(registry);
    scanner.addIncludeFilter(new AnnotationFilter());
    //获取配置的rpc扫描包下的所有bean定义
    for (String basePackage : packages) {
        Set<BeanDefinition> definitions = scanner.findCandidateComponents(basePackage);
        if (!CollectionUtils.isEmpty(definitions)) {
            for (BeanDefinition definition : definitions) {
                processConsumerAnnotation(definition);
                processProviderAnnotation(definition, registry);
            }
        }
    }

}
 
Example 2
Source Project: spring-boot-starter-grpc   Source File: GrpcAutoConfiguration.java    License: MIT License 6 votes vote down vote up
/**
 * 包扫描
 */
private Set<BeanDefinition> scanPackages(AnnotationMetadata importingClassMetadata, ClassPathBeanDefinitionScanner scanner) {
    List<String> packages = new ArrayList<>();
    Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(GrpcServiceScan.class.getCanonicalName());
    if (annotationAttributes != null) {
        String[] basePackages = (String[]) annotationAttributes.get("packages");
        if (basePackages.length > 0) {
            packages.addAll(Arrays.asList(basePackages));
        }
    }
    Set<BeanDefinition> beanDefinitions = new HashSet<>();
    if (CollectionUtils.isEmpty(packages)) {
        return beanDefinitions;
    }
    packages.forEach(pack -> beanDefinitions.addAll(scanner.findCandidateComponents(pack)));
    return beanDefinitions;
}
 
Example 3
Source Project: faster-framework-project   Source File: GRpcApiRegister.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(GRpcServerScan.class.getCanonicalName()));
    if (annotationAttributes == null) {
        log.warn("GrpcScan was not found.Please check your configuration.");
        return;
    }
    ClassPathBeanDefinitionScanner classPathGrpcApiScanner = new ClassPathBeanDefinitionScanner(registry, false);
    classPathGrpcApiScanner.setResourceLoader(this.resourceLoader);
    classPathGrpcApiScanner.addIncludeFilter(new AnnotationTypeFilter(GRpcApi.class));
    List<String> basePackages = AutoConfigurationPackages.get(this.beanFactory);
    for (String pkg : annotationAttributes.getStringArray("basePackages")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    classPathGrpcApiScanner.scan(StringUtils.toStringArray(basePackages));
}
 
Example 4
Source Project: dorado   Source File: SpringContainer.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized static void create(ApplicationContext applicationContext) {
	DoradoServerBuilder builder = Dorado.serverConfig;
	if (builder == null) {
		throw new IllegalStateException("Please init DoradoServer first!");
	}

	if (!(applicationContext instanceof DoradoApplicationContext)
			&& (applicationContext instanceof BeanDefinitionRegistry)) {
		ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(
				(BeanDefinitionRegistry) applicationContext);
		scanner.resetFilters(false);
		scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
		scanner.scan(builder.scanPackages());
	}

	instance = new SpringContainer(applicationContext);
	Dorado.springInitialized = true;
}
 
Example 5
Source Project: saluki   Source File: MonitorAutoconfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public BeanFactoryPostProcessor beanFactoryPostProcessor(ApplicationContext applicationContext) {
    return new BeanFactoryPostProcessor() {

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            if (beanFactory instanceof BeanDefinitionRegistry) {
                try {
                    BeanDefinitionRegistry registry = (BeanDefinitionRegistry)beanFactory;
                    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry);
                    scanner.setResourceLoader(applicationContext);
                    scanner.scan("io.github.saluki.monitor.rest");
                } catch (Throwable e) {
                    log.error(e.getMessage(), e);
                }
            }

        }

    };
}
 
Example 6
private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator(new BeanNameGenerator() {
		@Override
		public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
			return definition.getScope();
		}
	});
	scanner.setScopedProxyMode(scopedProxyMode);

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.refresh();
	return context;
}
 
Example 7
Source Project: spring-data-dev-tools   Source File: BootShim.java    License: Apache License 2.0 6 votes vote down vote up
public BootShim(String[] args, ConfigurableApplicationContext context) {
	this.ctx = context;

	try {
		commandLine = SimpleShellCommandLineOptions.parseCommandLine(args);
	} catch (IOException var5) {
		throw new ShellException(var5.getMessage(), var5);
	}

	this.configureApplicationContext(this.ctx);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner((BeanDefinitionRegistry) this.ctx);
	if (commandLine.getDisableInternalCommands()) {
		scanner.scan(new String[] { "org.springframework.shell.converters", "org.springframework.shell.plugin.support" });
	} else {
		scanner.scan(new String[] { "org.springframework.shell.commands", "org.springframework.shell.converters",
				"org.springframework.shell.plugin.support" });
	}

}
 
Example 8
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 5 votes vote down vote up
/**
 * Ensure that ContextLoaderListener and GenericWebApplicationContext interact nicely.
 */
@Test
public void genericWAC() {
	GenericWebApplicationContext ctx = new GenericWebApplicationContext();
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("bogus.pkg");

	cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}
 
Example 9
private ApplicationContext createContext(final ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
		@Override
		public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
			ScopeMetadata metadata = new ScopeMetadata();
			if (definition instanceof AnnotatedBeanDefinition) {
				AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
				for (String type : annDef.getMetadata().getAnnotationTypes()) {
					if (type.equals(javax.inject.Singleton.class.getName())) {
						metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
						break;
					}
					else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
						metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
						metadata.setScopedProxyMode(scopedProxyMode);
						break;
					}
					else if (type.startsWith("javax.inject")) {
						metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
					}
				}
			}
			return metadata;
		}
	});

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.registerAlias("classPathBeanDefinitionScannerJsr330ScopeIntegrationTests.SessionScopedTestBean", "session");
	context.refresh();
	return context;
}
 
Example 10
private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator((definition, registry) -> definition.getScope());
	scanner.setScopedProxyMode(scopedProxyMode);

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.refresh();
	return context;
}
 
Example 11
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedConfigClasses() {
	// it's actually ConfigurationClassPostProcessor's Environment that gets the job done here.
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan1");
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 12
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedComponents() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan2");
	ctx.refresh();
	assertThat(scanner.getEnvironment(), is((Environment)ctx.getEnvironment()));
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 13
Source Project: enode   Source File: EnodeBootstrapRegistrar.java    License: MIT License 5 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
    String declaringClass = metadata.getClass().getName();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false, this.environment, this.resourceLoader);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Command.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Event.class));
    AnnotationAttributes enodeScan = attributesFor(metadata, EnableEnode.class.getName());
    Set<String> basePackages = new LinkedHashSet<>();
    String[] basePackagesArray = enodeScan.getStringArray("basePackages");
    for (String pkg : basePackagesArray) {
        String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
                ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        Collections.addAll(basePackages, tokenized);
    }
    for (Class<?> clazz : enodeScan.getClassArray("basePackageClasses")) {
        basePackages.add(ClassUtils.getPackageName(clazz));
    }
    if (basePackages.isEmpty()) {
        basePackages.add(ClassUtils.getPackageName(metadata.getClassName()));
    }
    scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
        @Override
        protected boolean matchClassName(String className) {
            return declaringClass.equals(className);
        }
    });
    String[] scanPackages = StringUtils.toStringArray(basePackages);
    ObjectContainer.BASE_PACKAGES = scanPackages;
    scanner.scan(scanPackages);
}
 
Example 14
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 5 votes vote down vote up
/**
 * Ensure that ContextLoaderListener and GenericWebApplicationContext interact nicely.
 */
@Test
public void genericWAC() {
	GenericWebApplicationContext ctx = new GenericWebApplicationContext();
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("bogus.pkg");

	cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}
 
Example 15
private ApplicationContext createContext(final ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
		@Override
		public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
			ScopeMetadata metadata = new ScopeMetadata();
			if (definition instanceof AnnotatedBeanDefinition) {
				AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
				for (String type : annDef.getMetadata().getAnnotationTypes()) {
					if (type.equals(javax.inject.Singleton.class.getName())) {
						metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
						break;
					}
					else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
						metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
						metadata.setScopedProxyMode(scopedProxyMode);
						break;
					}
					else if (type.startsWith("javax.inject")) {
						metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
					}
				}
			}
			return metadata;
		}
	});

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.registerAlias("classPathBeanDefinitionScannerJsr330ScopeIntegrationTests.SessionScopedTestBean", "session");
	context.refresh();
	return context;
}
 
Example 16
private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator((definition, registry) -> definition.getScope());
	scanner.setScopedProxyMode(scopedProxyMode);

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.refresh();
	return context;
}
 
Example 17
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedConfigClasses() {
	// it's actually ConfigurationClassPostProcessor's Environment that gets the job done here.
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan1");
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 18
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedComponents() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan2");
	ctx.refresh();
	assertThat(scanner.getEnvironment(), is((Environment)ctx.getEnvironment()));
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 19
Source Project: spring-boot-starter-grpc   Source File: GrpcAutoConfiguration.java    License: MIT License 5 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    ClassPathBeanDefinitionScanner scanner = new ClassPathGrpcServiceScanner(registry);
    scanner.setResourceLoader(this.resourceLoader);
    scanner.addIncludeFilter(new AnnotationTypeFilter(GrpcService.class));
    Set<BeanDefinition> beanDefinitions = scanPackages(importingClassMetadata, scanner);
    ProxyUtil.registerBeans(beanFactory, beanDefinitions);
}
 
Example 20
/**
 * Scan base packages for register {@link Component @Component}s
 *
 * @param registry     {@link BeanDefinitionRegistry}
 * @param basePackages base packages
 * @return the count of registered components.
 */
public static int scanBasePackages(BeanDefinitionRegistry registry, String... basePackages) {

    int count = 0;

    if (!ObjectUtils.isEmpty(basePackages)) {

        boolean debugEnabled = logger.isDebugEnabled();

        if (debugEnabled) {
            logger.debug(registry.getClass().getSimpleName() + " will scan base packages " + Arrays.asList(basePackages) + ".");
        }

        List<String> registeredBeanNames = Arrays.asList(registry.getBeanDefinitionNames());

        ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(registry);
        count = classPathBeanDefinitionScanner.scan(basePackages);

        List<String> scannedBeanNames = new ArrayList<String>(count);
        scannedBeanNames.addAll(Arrays.asList(registry.getBeanDefinitionNames()));
        scannedBeanNames.removeAll(registeredBeanNames);

        if (debugEnabled) {
            logger.debug("The Scanned Components[ count : " + count + "] under base packages " + Arrays.asList(basePackages) + " : ");
        }

        for (String scannedBeanName : scannedBeanNames) {
            BeanDefinition scannedBeanDefinition = registry.getBeanDefinition(scannedBeanName);
            if (debugEnabled) {
                logger.debug("Component [ name : " + scannedBeanName + " , class : " + scannedBeanDefinition.getBeanClassName() + " ]");
            }
        }
    }

    return count;

}
 
Example 21
Source Project: conf4j   Source File: ConfigurationScanBeanDefinitionParser.java    License: MIT License 5 votes vote down vote up
@Override
protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) {
    ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element);

    getAnnotationClasses(parserContext, element, scanner.getResourceLoader().getClassLoader())
            .forEach((clazz) -> scanner.addIncludeFilter(new AnnotationTypeFilter(clazz)));

    return scanner;
}
 
Example 22
Source Project: hdfs-shell   Source File: BootShim.java    License: Apache License 2.0 5 votes vote down vote up
public BootShim(String[] args, ConfigurableApplicationContext context) {
    this.ctx = context;
    try {
        commandLine = SimpleShellCommandLineOptions.parseCommandLine(args);
    } catch (IOException var5) {
        throw new ShellException(var5.getMessage(), var5);
    }
    this.configureApplicationContext(this.ctx);
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner((BeanDefinitionRegistry) this.ctx);
    if (commandLine.getDisableInternalCommands()) {
        scanner.scan("org.springframework.shell.converters", "org.springframework.shell.plugin.support");
    } else {
        scanner.scan("org.springframework.shell.commands", "org.springframework.shell.converters", "org.springframework.shell.plugin.support");
    }
}
 
Example 23
/**
 * Loads {@link BeanDefinition BeanDefinitions} from Annotation configuration (component) classes
 * as well as from other resource locations (e.g. XML).
 *
 * @param beanFactory {@link DefaultListableBeanFactory} to configure.
 * @throws BeansException if loading and configuring the {@link BeanDefinition BeanDefintions} for the target
 * {@link DefaultListableBeanFactory} fails.
 * @see org.springframework.beans.factory.support.DefaultListableBeanFactory
 * @see #newAnnotatedBeanDefinitionReader(BeanDefinitionRegistry)
 * @see #newClassBeanDefinitionScanner(BeanDefinitionRegistry)
 * @see #getConfigLocations()
 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException {

	AnnotatedBeanDefinitionReader reader = configure(newAnnotatedBeanDefinitionReader(beanFactory));

	ClassPathBeanDefinitionScanner scanner = configure(newClassBeanDefinitionScanner(beanFactory));

	getBeanNameGenerator().ifPresent(beanNameGenerator -> {
		reader.setBeanNameGenerator(beanNameGenerator);
		scanner.setBeanNameGenerator(beanNameGenerator);
		beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
	});

	getScopeMetadataResolver().ifPresent(scopeMetadataResolver -> {
		reader.setScopeMetadataResolver(scopeMetadataResolver);
		scanner.setScopeMetadataResolver(scopeMetadataResolver);
	});

	Arrays.stream(ArrayUtils.nullSafeArray(getConfigLocations(), String.class)).forEach(configLocation -> {
		try {
			Class<?> type = ClassUtils.forName(configLocation, getClassLoader());
			getLogger().trace("Registering [{}]", configLocation);
			reader.register(type);
		}
		catch (ClassNotFoundException cause) {

			getLogger().trace(String.format("Could not load class for config location [%s] - trying package scan.",
				configLocation), cause);

			if (scanner.scan(configLocation) == 0) {
				getLogger().debug("No component classes found for specified class/package [{}]", configLocation);
			}
		}
	});
}
 
Example 24
private ClassPathBeanDefinitionScanner configure(ClassPathBeanDefinitionScanner scanner) {

		Set<String> basePackages = this.basePackages;

		if (!basePackages.isEmpty()) {
			getLogger().debug("Scanning base packages: {}", basePackages);
			scanner.scan(StringUtils.toStringArray(basePackages));
		}

		return scanner;
	}
 
Example 25
Source Project: spring4-understanding   Source File: Spr8510Tests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ensure that ContextLoaderListener and GenericWebApplicationContext interact nicely.
 */
@Test
public void genericWAC() {
	GenericWebApplicationContext ctx = new GenericWebApplicationContext();
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("bogus.pkg");

	cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}
 
Example 26
private ApplicationContext createContext(final ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
		@Override
		public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
			ScopeMetadata metadata = new ScopeMetadata();
			if (definition instanceof AnnotatedBeanDefinition) {
				AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
				for (String type : annDef.getMetadata().getAnnotationTypes()) {
					if (type.equals(javax.inject.Singleton.class.getName())) {
						metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
						break;
					}
					else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
						metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
						metadata.setScopedProxyMode(scopedProxyMode);
						break;
					}
					else if (type.startsWith("javax.inject")) {
						metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
					}
				}
			}
			return metadata;
		}
	});

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.registerAlias("classPathBeanDefinitionScannerJsr330ScopeIntegrationTests.SessionScopedTestBean", "session");
	context.refresh();
	return context;
}
 
Example 27
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedConfigClasses() {
	// it's actually ConfigurationClassPostProcessor's Environment that gets the job done here.
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan1");
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 28
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedComponents() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan2");
	ctx.refresh();
	assertThat(scanner.getEnvironment(), is((Environment)ctx.getEnvironment()));
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 29
Source Project: msf4j   Source File: MSF4JSpringApplication.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This will add a given service class to the running instance with given base path.
 *
 * @param configurableApplicationContext ConfigurableApplicationContext of running app
 * @param serviceClass                   Service class
 * @param basePath                       Base path to which the service get registered
 */
public SpringMicroservicesRunner addService(ConfigurableApplicationContext configurableApplicationContext,
                                            Class<?> serviceClass, String basePath) {
    ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner =
            new ClassPathBeanDefinitionScanner((BeanDefinitionRegistry) configurableApplicationContext);
    classPathBeanDefinitionScanner.scan(serviceClass.getPackage().getName());
    SpringMicroservicesRunner springMicroservicesRunner =
            configurableApplicationContext.getBean(SpringMicroservicesRunner.class);
    springMicroservicesRunner.deploy(basePath, configurableApplicationContext.getBean(serviceClass));
    return springMicroservicesRunner;
}
 
Example 30
/**
 * Return an agent instance for a scanner. If the instance does not exists yet, it is created.
 *
 * @param scanner the scanner
 * @return agent instance
 */
public static ClassPathBeanDefinitionScannerAgent getInstance(ClassPathBeanDefinitionScanner scanner) {
    ClassPathBeanDefinitionScannerAgent classPathBeanDefinitionScannerAgent = instances.get(scanner);
    // registry may be different if there is multiple app. (this is just a temporary solution)
    if (classPathBeanDefinitionScannerAgent == null || classPathBeanDefinitionScannerAgent.registry != scanner.getRegistry()) {
        instances.put(scanner, new ClassPathBeanDefinitionScannerAgent(scanner));
    }
    return instances.get(scanner);
}