org.springframework.context.annotation.ClassPathBeanDefinitionScanner Java Examples

The following examples show how to use org.springframework.context.annotation.ClassPathBeanDefinitionScanner. 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 File: GrpcAutoConfiguration.java    From spring-boot-starter-grpc with 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 #2
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: BootShim.java    From spring-data-dev-tools with 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 #4
Source File: MonitorAutoconfiguration.java    From saluki with 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 #5
Source File: SpringContainer.java    From dorado with 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 #6
Source File: GRpcApiRegister.java    From faster-framework-project with 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 #7
Source File: RpcDefinitionPostProcessor.java    From joyrpc with 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 #8
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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 #9
Source File: RefreshableAnnotationConfigApplicationContext.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: RefreshableAnnotationConfigApplicationContext.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #11
Source File: MSF4JSpringApplication.java    From msf4j with 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 #12
Source File: ClassPathBeanDefinitionScannerAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #13
Source File: Spr8510Tests.java    From spring-analysis-note with 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 #14
Source File: BootShim.java    From hdfs-shell with 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 #15
Source File: ConfigurationScanBeanDefinitionParser.java    From conf4j with 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 #16
Source File: ClassPathBeanDefinitionScannerAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private ClassPathBeanDefinitionScannerAgent(ClassPathBeanDefinitionScanner scanner) {
    this.scanner = scanner;

    this.registry = scanner.getRegistry();
    this.scopeMetadataResolver = (ScopeMetadataResolver) ReflectionHelper.get(scanner, "scopeMetadataResolver");
    this.beanNameGenerator = (BeanNameGenerator) ReflectionHelper.get(scanner, "beanNameGenerator");
}
 
Example #17
Source File: EnvironmentSystemIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: AnnotatedBeanDefinitionRegistryUtils.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #19
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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 #20
Source File: EnvironmentSystemIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #21
Source File: Spr8510Tests.java    From spring4-understanding with 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 #22
Source File: GrpcAutoConfiguration.java    From spring-boot-starter-grpc with 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 #23
Source File: EnvironmentSystemIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #24
Source File: EnvironmentSystemIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #25
Source File: EnvironmentSystemIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #26
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
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 #27
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
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 #28
Source File: Spr8510Tests.java    From java-technology-stack with 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 #29
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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 #30
Source File: XmlBeanDefinitionScannerAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private XmlBeanDefinitionScannerAgent(BeanDefinitionReader reader) {
    this.reader = reader;

    if (SpringPlugin.basePackagePrefixes != null && !basePackageInited) {
        ClassPathBeanDefinitionScannerAgent xmlBeanDefinitionScannerAgent = ClassPathBeanDefinitionScannerAgent.getInstance(new ClassPathBeanDefinitionScanner(reader.getRegistry()));
        for (String basePackage : SpringPlugin.basePackagePrefixes) {
            xmlBeanDefinitionScannerAgent.registerBasePackage(basePackage);
        }
        basePackageInited = true;
    }
}