org.springframework.context.annotation.AnnotatedBeanDefinitionReader Java Examples

The following examples show how to use org.springframework.context.annotation.AnnotatedBeanDefinitionReader. 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: EnvironmentSecurityManagerIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentButAllowsAccessToIndividualKeys() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(true));
}
 
Example #2
Source File: SpringAtInjectTck.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public static Test suite() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotatedBeanDefinitionReader bdr = new AnnotatedBeanDefinitionReader(ac);
	bdr.setScopeMetadataResolver(new Jsr330ScopeMetadataResolver());

	bdr.registerBean(Convertible.class);
	bdr.registerBean(DriversSeat.class, Drivers.class);
	bdr.registerBean(Seat.class, Primary.class);
	bdr.registerBean(V8Engine.class);
	bdr.registerBean(SpareTire.class, "spare");
	bdr.registerBean(Cupholder.class);
	bdr.registerBean(Tire.class, Primary.class);
	bdr.registerBean(FuelTank.class);

	ac.refresh();
	Car car = ac.getBean(Car.class);

	return Tck.testsFor(car, false, true);
}
 
Example #3
Source File: EnvironmentSecurityManagerIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentButAllowsAccessToIndividualKeys() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(true));
}
 
Example #4
Source File: CustomRequestAttributesRequestContextHolderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	ServletContext servletContext = new MockServletContext();
	MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext);
	mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK);
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse()));

	this.wac.setServletContext(servletContext);
	new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class);
	this.wac.refresh();

	this.mockMvc = webAppContextSetup(this.wac)
			.defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT))
			.alwaysExpect(status().isOk())
			.build();
}
 
Example #5
Source File: CustomRequestAttributesRequestContextHolderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setUp() {
	ServletContext servletContext = new MockServletContext();
	MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext);
	mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK);
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse()));

	this.wac.setServletContext(servletContext);
	new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class);
	this.wac.refresh();

	this.mockMvc = webAppContextSetup(this.wac)
			.defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT))
			.alwaysExpect(status().isOk())
			.build();
}
 
Example #6
Source File: SpringAtInjectTck.java    From java-technology-stack with MIT License 6 votes vote down vote up
public static Test suite() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotatedBeanDefinitionReader bdr = new AnnotatedBeanDefinitionReader(ac);
	bdr.setScopeMetadataResolver(new Jsr330ScopeMetadataResolver());

	bdr.registerBean(Convertible.class);
	bdr.registerBean(DriversSeat.class, Drivers.class);
	bdr.registerBean(Seat.class, Primary.class);
	bdr.registerBean(V8Engine.class);
	bdr.registerBean(SpareTire.class, "spare");
	bdr.registerBean(Cupholder.class);
	bdr.registerBean(Tire.class, Primary.class);
	bdr.registerBean(FuelTank.class);

	ac.refresh();
	Car car = ac.getBean(Car.class);

	return Tck.testsFor(car, false, true);
}
 
Example #7
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void cronTaskWithScopedProxy() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	new AnnotatedBeanDefinitionReader(context).register(ProxiedCronTestBean.class, ProxiedCronTestBeanDependent.class);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(1, postProcessor.getScheduledTasks().size());

	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(context.getBean(ScopedProxyUtils.getTargetBeanName("target")), targetObject);
	assertEquals("cron", targetMethod.getName());
	assertEquals("*/7 * * * * ?", task.getExpression());
}
 
Example #8
Source File: AnnotatedBeanDefinitionParsingDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    // 基于 Java 注解的 AnnotatedBeanDefinitionReader 的实现
    AnnotatedBeanDefinitionReader beanDefinitionReader = new AnnotatedBeanDefinitionReader(beanFactory);
    int beanDefinitionCountBefore = beanFactory.getBeanDefinitionCount();
    // 注册当前类(非 @Component class)
    beanDefinitionReader.register(AnnotatedBeanDefinitionParsingDemo.class);
    int beanDefinitionCountAfter = beanFactory.getBeanDefinitionCount();
    int beanDefinitionCount = beanDefinitionCountAfter - beanDefinitionCountBefore;
    System.out.println("已加载 BeanDefinition 数量:" + beanDefinitionCount);
    // 普通的 Class 作为 Component 注册到 Spring IoC 容器后,通常 Bean 名称为 annotatedBeanDefinitionParsingDemo
    // Bean 名称生成来自于 BeanNameGenerator,注解实现 AnnotationBeanNameGenerator
    AnnotatedBeanDefinitionParsingDemo demo = beanFactory.getBean("annotatedBeanDefinitionParsingDemo",
            AnnotatedBeanDefinitionParsingDemo.class);
    System.out.println(demo);
}
 
Example #9
Source File: EngineBeanDefinitionParser.java    From score with Apache License 2.0 6 votes vote down vote up
private void loadContexts(Element element, BeanDefinitionRegistry beanDefinitionRegistry) {
    String externalDatabase = element.getAttribute("externalDatabase");
    if (StringUtils.isBlank(externalDatabase) || externalDatabase.equals(Boolean.FALSE.toString())) {
        AnnotatedBeanDefinitionReader definitionReader = new AnnotatedBeanDefinitionReader(beanDefinitionRegistry);
        definitionReader.register(ScoreDefaultDatasourceContext.class);
        definitionReader.register(ScoreDatabaseContext.class);
    }

    String repositoriesContextPath = "META-INF/spring/score/context/scoreRepositoryContext.xml";

    String ignoreEngineJobs = element.getAttribute("ignoreEngineJobs");
    if(StringUtils.isNotBlank(ignoreEngineJobs) && ignoreEngineJobs.equals(Boolean.TRUE.toString())){
        new XmlBeanDefinitionReader(beanDefinitionRegistry).loadBeanDefinitions(repositoriesContextPath);
    }
    else{
        new XmlBeanDefinitionReader(beanDefinitionRegistry).loadBeanDefinitions(repositoriesContextPath,ENGINE_JOBS_CONTEXT_LOCATION);
    }
}
 
Example #10
Source File: SpringAtInjectTck.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public static Test suite() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotatedBeanDefinitionReader bdr = new AnnotatedBeanDefinitionReader(ac);
	bdr.setScopeMetadataResolver(new Jsr330ScopeMetadataResolver());

	bdr.registerBean(Convertible.class);
	bdr.registerBean(DriversSeat.class, Drivers.class);
	bdr.registerBean(Seat.class, Primary.class);
	bdr.registerBean(V8Engine.class);
	bdr.registerBean(SpareTire.class, "spare");
	bdr.registerBean(Cupholder.class);
	bdr.registerBean(Tire.class, Primary.class);
	bdr.registerBean(FuelTank.class);

	ac.refresh();
	Car car = ac.getBean(Car.class);

	return Tck.testsFor(car, false, true);
}
 
Example #11
Source File: EnvironmentSecurityManagerIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentButAllowsAccessToIndividualKeys() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(true));
}
 
Example #12
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void cronTaskWithScopedProxy() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	new AnnotatedBeanDefinitionReader(context).register(ProxiedCronTestBean.class, ProxiedCronTestBeanDependent.class);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(1, postProcessor.getScheduledTasks().size());

	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(context.getBean(ScopedProxyUtils.getTargetBeanName("target")), targetObject);
	assertEquals("cron", targetMethod.getName());
	assertEquals("*/7 * * * * ?", task.getExpression());
}
 
Example #13
Source File: CustomRequestAttributesRequestContextHolderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setUp() {
	ServletContext servletContext = new MockServletContext();
	MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext);
	mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK);
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse()));

	this.wac.setServletContext(servletContext);
	new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class);
	this.wac.refresh();

	this.mockMvc = webAppContextSetup(this.wac)
			.defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT))
			.alwaysExpect(status().isOk())
			.build();
}
 
Example #14
Source File: AnnotationConfigWebContextLoader.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Register classes in the supplied {@linkplain GenericWebApplicationContext context}
 * from the classes in the supplied {@link WebMergedContextConfiguration}.
 * <p>Each class must represent an <em>annotated class</em>. An
 * {@link AnnotatedBeanDefinitionReader} is used to register the appropriate
 * bean definitions.
 * @param context the context in which the annotated classes should be registered
 * @param webMergedConfig the merged configuration from which the classes should be retrieved
 * @see AbstractGenericWebContextLoader#loadBeanDefinitions
 */
@Override
protected void loadBeanDefinitions(
		GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {

	Class<?>[] annotatedClasses = webMergedConfig.getClasses();
	if (logger.isDebugEnabled()) {
		logger.debug("Registering annotated classes: " + ObjectUtils.nullSafeToString(annotatedClasses));
	}
	new AnnotatedBeanDefinitionReader(context).register(annotatedClasses);
}
 
Example #15
Source File: RefreshableAnnotationConfigApplicationContext.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
private AnnotatedBeanDefinitionReader configure(AnnotatedBeanDefinitionReader reader) {

		Set<Class<?>> componentClasses = this.componentClasses;

		if (!componentClasses.isEmpty()) {
			getLogger().debug("Registering component classes: {}", componentClasses);
			reader.register(ClassUtils.toClassArray(componentClasses));
		}

		return reader;
	}
 
Example #16
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 #17
Source File: EnvironmentSecurityManagerIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
			// Disallowing access to the spring.profiles.active property means that
			// the BeanDefinitionReader won't be able to determine which profiles are
			// active. We should see an INFO-level message in the console about this
			// and as a result, any components marked with a non-default profile will
			// be ignored.
			if (("getenv." + AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) {
				throw new AccessControlException(
						format("Accessing system environment variable [%s] is disallowed",
								AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME));
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(false));
}
 
Example #18
Source File: AnnotatedBeanDefinitionRegistryUtils.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
/**
 * Register Beans if not present in {@link BeanDefinitionRegistry registry}
 *
 * @param registry         {@link BeanDefinitionRegistry}
 * @param annotatedClasses {@link Annotation annotation} class
 */
public static void registerBeans(BeanDefinitionRegistry registry, Class<?>... annotatedClasses) {

    if (ObjectUtils.isEmpty(annotatedClasses)) {
        return;
    }

    Set<Class<?>> classesToRegister = new LinkedHashSet<Class<?>>(asList(annotatedClasses));

    // Remove all annotated-classes that have been registered
    Iterator<Class<?>> iterator = classesToRegister.iterator();

    while (iterator.hasNext()) {
        Class<?> annotatedClass = iterator.next();
        if (isPresentBean(registry, annotatedClass)) {
            iterator.remove();
        }
    }

    AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(registry);

    if (logger.isDebugEnabled()) {
        logger.debug(registry.getClass().getSimpleName() + " will register annotated classes : " + asList(annotatedClasses) + " .");
    }

    reader.register(classesToRegister.toArray(EMPTY_CLASS_ARRAY));

}
 
Example #19
Source File: EnvironmentSystemIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void annotatedBeanDefinitionReader_inheritsEnvironmentFromEnvironmentCapableBDR() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	new AnnotatedBeanDefinitionReader(ctx).register(Config.class);
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example #20
Source File: EnvironmentSecurityManagerIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
			// Disallowing access to the spring.profiles.active property means that
			// the BeanDefinitionReader won't be able to determine which profiles are
			// active. We should see an INFO-level message in the console about this
			// and as a result, any components marked with a non-default profile will
			// be ignored.
			if (("getenv." + AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) {
				throw new AccessControlException(
						format("Accessing system environment variable [%s] is disallowed",
								AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME));
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(false));
}
 
Example #21
Source File: EnvironmentSystemIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void annotatedBeanDefinitionReader_inheritsEnvironmentFromEnvironmentCapableBDR() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	new AnnotatedBeanDefinitionReader(ctx).register(Config.class);
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example #22
Source File: SpringInitializer.java    From Mycat-openEP with Apache License 2.0 5 votes vote down vote up
private static void initAnnotatedConf(GenericApplicationContext context){
	Class componentScanAnnotated=ProcessInfo.getAnnotationInitClass();
	if(componentScanAnnotated!=null){
		AnnotatedGenericBeanDefinition def=new AnnotatedGenericBeanDefinition(ProcessInfo.getAnnotationInitClass());
		AnnotatedBeanDefinitionReader reader=new AnnotatedBeanDefinitionReader(context);
		AnnotationScopeMetadataResolver resolver=new AnnotationScopeMetadataResolver();
		resolver.resolveScopeMetadata(def);
		reader.setScopeMetadataResolver(resolver);
	}
}
 
Example #23
Source File: EnvironmentSecurityManagerIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
			// Disallowing access to the spring.profiles.active property means that
			// the BeanDefinitionReader won't be able to determine which profiles are
			// active. We should see an INFO-level message in the console about this
			// and as a result, any components marked with a non-default profile will
			// be ignored.
			if (("getenv." + AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) {
				throw new AccessControlException(
						format("Accessing system environment variable [%s] is disallowed",
								AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME));
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(false));
}
 
Example #24
Source File: EnvironmentSystemIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void annotatedBeanDefinitionReader_inheritsEnvironmentFromEnvironmentCapableBDR() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	new AnnotatedBeanDefinitionReader(ctx).register(Config.class);
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example #25
Source File: AnnotationConfigWebContextLoader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Register classes in the supplied {@linkplain GenericWebApplicationContext context}
 * from the classes in the supplied {@link WebMergedContextConfiguration}.
 * <p>Each class must represent an <em>annotated class</em>. An
 * {@link AnnotatedBeanDefinitionReader} is used to register the appropriate
 * bean definitions.
 * @param context the context in which the annotated classes should be registered
 * @param webMergedConfig the merged configuration from which the classes should be retrieved
 * @see AbstractGenericWebContextLoader#loadBeanDefinitions
 */
@Override
protected void loadBeanDefinitions(
		GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {

	Class<?>[] annotatedClasses = webMergedConfig.getClasses();
	if (logger.isDebugEnabled()) {
		logger.debug("Registering annotated classes: " + ObjectUtils.nullSafeToString(annotatedClasses));
	}
	new AnnotatedBeanDefinitionReader(context).register(annotatedClasses);
}
 
Example #26
Source File: InitializerWithoutConfigFilesOrClassesTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
	new AnnotatedBeanDefinitionReader(applicationContext).register(GlobalConfig.class);
}
 
Example #27
Source File: HybridContextLoader.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {
	// Order doesn't matter: <bean> always wins over @Bean.
	new XmlBeanDefinitionReader(context).loadBeanDefinitions(mergedConfig.getLocations());
	new AnnotatedBeanDefinitionReader(context).register(mergedConfig.getClasses());
}
 
Example #28
Source File: AnnotationConfigApplicationContext.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new AnnotationConfigApplicationContext that needs to be populated
 * through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
 */
public AnnotationConfigApplicationContext() {
	this.reader = new AnnotatedBeanDefinitionReader(this);
	this.scanner = new ClassPathBeanDefinitionScanner(this);
}
 
Example #29
Source File: AnnotationConfigWebApplicationContext.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Register a {@link org.springframework.beans.factory.config.BeanDefinition} for
 * any classes specified by {@link #register(Class...)} and scan any packages
 * specified by {@link #scan(String...)}.
 * <p>For any values specified by {@link #setConfigLocation(String)} or
 * {@link #setConfigLocations(String[])}, attempt first to load each location as a
 * class, registering a {@code BeanDefinition} if class loading is successful,
 * and if class loading fails (i.e. a {@code ClassNotFoundException} is raised),
 * assume the value is a package and attempt to scan it for annotated classes.
 * <p>Enables the default set of annotation configuration post processors, such that
 * {@code @Autowired}, {@code @Required}, and associated annotations can be used.
 * <p>Configuration class bean definitions are registered with generated bean
 * definition names unless the {@code value} attribute is provided to the stereotype
 * annotation.
 * @param beanFactory the bean factory to load bean definitions into
 * @see #register(Class...)
 * @see #scan(String...)
 * @see #setConfigLocation(String)
 * @see #setConfigLocations(String[])
 * @see AnnotatedBeanDefinitionReader
 * @see ClassPathBeanDefinitionScanner
 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
	AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory);
	ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory);

	BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
	if (beanNameGenerator != null) {
		reader.setBeanNameGenerator(beanNameGenerator);
		scanner.setBeanNameGenerator(beanNameGenerator);
		beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
	}

	ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
	if (scopeMetadataResolver != null) {
		reader.setScopeMetadataResolver(scopeMetadataResolver);
		scanner.setScopeMetadataResolver(scopeMetadataResolver);
	}

	if (!this.annotatedClasses.isEmpty()) {
		if (logger.isInfoEnabled()) {
			logger.info("Registering annotated classes: [" +
					StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
		}
		reader.register(this.annotatedClasses.toArray(new Class<?>[this.annotatedClasses.size()]));
	}

	if (!this.basePackages.isEmpty()) {
		if (logger.isInfoEnabled()) {
			logger.info("Scanning base packages: [" +
					StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
		}
		scanner.scan(this.basePackages.toArray(new String[this.basePackages.size()]));
	}

	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		for (String configLocation : configLocations) {
			try {
				Class<?> clazz = getClassLoader().loadClass(configLocation);
				if (logger.isInfoEnabled()) {
					logger.info("Successfully resolved class for [" + configLocation + "]");
				}
				reader.register(clazz);
			}
			catch (ClassNotFoundException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Could not load class for config location [" + configLocation +
							"] - trying package scan. " + ex);
				}
				int count = scanner.scan(configLocation);
				if (logger.isInfoEnabled()) {
					if (count == 0) {
						logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
					}
					else {
						logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
					}
				}
			}
		}
	}
}
 
Example #30
Source File: AnnotationConfigWebApplicationContext.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
/**
 * Register a {@link org.springframework.beans.factory.config.BeanDefinition} for
 * any classes specified by {@link #register(Class...)} and scan any packages
 * specified by {@link #scan(String...)}.
 * <p>For any values specified by {@link #setConfigLocation(String)} or
 * {@link #setConfigLocations(String[])}, attempt first to load each location as a
 * class, registering a {@code BeanDefinition} if class loading is successful,
 * and if class loading fails (i.e. a {@code ClassNotFoundException} is raised),
 * assume the value is a package and attempt to scan it for annotated classes.
 * <p>Enables the default set of annotation configuration post processors, such that
 * {@code @Autowired}, {@code @Required}, and associated annotations can be used.
 * <p>Configuration class bean definitions are registered with generated bean
 * definition names unless the {@code value} attribute is provided to the stereotype
 * annotation.
 * @see #register(Class...)
 * @see #scan(String...)
 * @see #setConfigLocation(String)
 * @see #setConfigLocations(String[])
 * @see AnnotatedBeanDefinitionReader
 * @see ClassPathBeanDefinitionScanner
 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
    AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(beanFactory);
    reader.setEnvironment(this.getEnvironment());

    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanFactory);
    scanner.setEnvironment(this.getEnvironment());

    BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
    ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
    if (beanNameGenerator != null) {
        reader.setBeanNameGenerator(beanNameGenerator);
        scanner.setBeanNameGenerator(beanNameGenerator);
        beanFactory.registerSingleton(
                AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
    }
    if (scopeMetadataResolver != null) {
        reader.setScopeMetadataResolver(scopeMetadataResolver);
        scanner.setScopeMetadataResolver(scopeMetadataResolver);
    }

    if (!this.annotatedClasses.isEmpty()) {
        if (logger.isInfoEnabled()) {
            logger.info("Registering annotated classes: [" +
                    StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
        }
        reader.register(this.annotatedClasses.toArray(new Class<?>[0]));
    }

    if (!this.basePackages.isEmpty()) {
        if (logger.isInfoEnabled()) {
            logger.info("Scanning base packages: [" +
                    StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
        }
        for (TypeFilter typeFilter : includeFilters) {
            scanner.addIncludeFilter(typeFilter);
        }
        scanner.scan(this.basePackages.toArray(new String[0]));
    }

    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
        for (String configLocation : configLocations) {
            try {
                Class<?> clazz = getClassLoader().loadClass(configLocation);
                if (logger.isInfoEnabled()) {
                    logger.info("Successfully resolved class for [" + configLocation + "]");
                }
                reader.register(clazz);
            }
            catch (ClassNotFoundException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not load class for config location [" + configLocation +
                            "] - trying package scan. " + ex);
                }
                int count = scanner.scan(configLocation);
                if (logger.isInfoEnabled()) {
                    if (count == 0) {
                        logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
                    }
                    else {
                        logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
                    }
                }
            }
        }
    }
}