org.springframework.beans.factory.support.RootBeanDefinition Java Examples

The following examples show how to use org.springframework.beans.factory.support.RootBeanDefinition. 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: TargetBeanFilterTest.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void target2() {
    Properties properties = new Properties();
    properties.put(SpringBeansConfig.SPRING_BEANS_PREFIX + 1 + SpringBeansConfig.SPRING_BEANS_NAME_PATTERN_POSTFIX, "");
    properties.put(SpringBeansConfig.SPRING_BEANS_PREFIX + 1 + SpringBeansConfig.SPRING_BEANS_CLASS_PATTERN_POSTFIX, "");
    properties.put(SpringBeansConfig.SPRING_BEANS_PREFIX + 1 + SpringBeansConfig.SPRING_BEANS_ANNOTATION_POSTFIX, "");

    properties.put(SpringBeansConfig.SPRING_BEANS_PREFIX + 2 + SpringBeansConfig.SPRING_BEANS_NAME_PATTERN_POSTFIX, "Target.*");

    ProfilerConfig config = new DefaultProfilerConfig(properties);
    TargetBeanFilter filter = TargetBeanFilter.of(config);
    filter.clear();

    BeanDefinition beanDefinition = new RootBeanDefinition(String.class);

    assertTrue(filter.isTarget(SpringBeansTargetScope.COMPONENT_SCAN, "Target0", beanDefinition));
}
 
Example #2
Source File: CommonAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testResourceInjection() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
	bpp.setResourceFactory(bf);
	bf.addBeanPostProcessor(bpp);
	bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ResourceInjectionBean.class));
	TestBean tb = new TestBean();
	bf.registerSingleton("testBean", tb);
	TestBean tb2 = new TestBean();
	bf.registerSingleton("testBean2", tb2);

	ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
	assertTrue(bean.initCalled);
	assertTrue(bean.init2Called);
	assertTrue(bean.init3Called);
	assertSame(tb, bean.getTestBean());
	assertSame(tb2, bean.getTestBean2());
	bf.destroySingletons();
	assertTrue(bean.destroyCalled);
	assertTrue(bean.destroy2Called);
	assertTrue(bean.destroy3Called);
}
 
Example #3
Source File: DDDBeanRegistryPostProcessor.java    From flower with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  Set<String> serviceTypes = new HashSet<>();
  Class<?> services[] =
      new Class<?>[] {CommandHandlerService.class, EventHandlerService.class, QueryHandlerService.class,
          DDDStartService.class, DDDEndService.class, DefaultCommandGateway.class, DefaultQueryGateway.class};

  for (Class<?> service : services) {
    BeanDefinition beanDefinition = new RootBeanDefinition(service);
    String handlerServiceName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, registry);
    registry.registerBeanDefinition(handlerServiceName, beanDefinition);
    if (Service.class.isAssignableFrom(service)) {
      serviceTypes.add(service.getName());
    }
  }

  final String dddFactoryName = "dddFactory";
  if (registry.containsBeanDefinition(dddFactoryName)) {
    BeanDefinition dddFactoryBeanDefinition = registry.getBeanDefinition(dddFactoryName);
    dddFactoryBeanDefinition.getPropertyValues().add("serviceTypes", serviceTypes);
  }

}
 
Example #4
Source File: JmsListenerContainerParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected RootBeanDefinition createContainerFactory(String factoryId, Element containerEle, ParserContext parserContext,
		PropertyValues commonContainerProperties, PropertyValues specificContainerProperties) {

	RootBeanDefinition factoryDef = new RootBeanDefinition();

	String containerType = containerEle.getAttribute(CONTAINER_TYPE_ATTRIBUTE);
	String containerClass = containerEle.getAttribute(CONTAINER_CLASS_ATTRIBUTE);
	if (!"".equals(containerClass)) {
		return null; // Not supported
	}
	else if ("".equals(containerType) || containerType.startsWith("default")) {
		factoryDef.setBeanClassName("org.springframework.jms.config.DefaultJmsListenerContainerFactory");
	}
	else if (containerType.startsWith("simple")) {
		factoryDef.setBeanClassName("org.springframework.jms.config.SimpleJmsListenerContainerFactory");
	}

	factoryDef.getPropertyValues().addPropertyValues(commonContainerProperties);
	factoryDef.getPropertyValues().addPropertyValues(specificContainerProperties);

	return factoryDef;
}
 
Example #5
Source File: AnnotationAsyncExecutionAspectTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void qualifiedAsyncMethodsAreRoutedToCorrectExecutor() throws InterruptedException, ExecutionException {
	DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
	beanFactory.registerBeanDefinition("e1", new RootBeanDefinition(ThreadPoolTaskExecutor.class));
	AnnotationAsyncExecutionAspect.aspectOf().setBeanFactory(beanFactory);

	ClassWithQualifiedAsyncMethods obj = new ClassWithQualifiedAsyncMethods();

	Future<Thread> defaultThread = obj.defaultWork();
	assertThat(defaultThread.get(), not(Thread.currentThread()));
	assertThat(defaultThread.get().getName(), not(startsWith("e1-")));

	ListenableFuture<Thread> e1Thread = obj.e1Work();
	assertThat(e1Thread.get().getName(), startsWith("e1-"));

	CompletableFuture<Thread> e1OtherThread = obj.e1OtherWork();
	assertThat(e1OtherThread.get().getName(), startsWith("e1-"));
}
 
Example #6
Source File: MessageBrokerBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private ManagedMap<String, Object> registerHandlerMapping(Element element,
		ParserContext context, Object source) {

	RootBeanDefinition handlerMappingDef = new RootBeanDefinition(WebSocketHandlerMapping.class);

	String orderAttribute = element.getAttribute("order");
	int order = orderAttribute.isEmpty() ? DEFAULT_MAPPING_ORDER : Integer.valueOf(orderAttribute);
	handlerMappingDef.getPropertyValues().add("order", order);

	String pathHelper = element.getAttribute("path-helper");
	if (StringUtils.hasText(pathHelper)) {
		handlerMappingDef.getPropertyValues().add("urlPathHelper", new RuntimeBeanReference(pathHelper));
	}

	ManagedMap<String, Object> urlMap = new ManagedMap<String, Object>();
	urlMap.setSource(source);
	handlerMappingDef.getPropertyValues().add("urlMap", urlMap);

	registerBeanDef(handlerMappingDef, context, source);
	return urlMap;
}
 
Example #7
Source File: ConfigurationClassProcessingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void configurationWithPostProcessor() {
	AnnotationConfigApplicationContext factory = new AnnotationConfigApplicationContext();
	factory.register(ConfigWithPostProcessor.class);
	RootBeanDefinition placeholderConfigurer = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
	placeholderConfigurer.getPropertyValues().add("properties", "myProp=myValue");
	factory.registerBeanDefinition("placeholderConfigurer", placeholderConfigurer);
	factory.refresh();

	TestBean foo = factory.getBean("foo", TestBean.class);
	ITestBean bar = factory.getBean("bar", ITestBean.class);
	ITestBean baz = factory.getBean("baz", ITestBean.class);

	assertEquals("foo-processed-myValue", foo.getName());
	assertEquals("bar-processed-myValue", bar.getName());
	assertEquals("baz-processed-myValue", baz.getName());

	SpousyTestBean listener = factory.getBean("listenerTestBean", SpousyTestBean.class);
	assertTrue(listener.refreshed);
}
 
Example #8
Source File: ConfigurationClassPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCircularDependency() {
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(beanFactory);
	beanFactory.addBeanPostProcessor(bpp);
	beanFactory.registerBeanDefinition("configClass1", new RootBeanDefinition(A.class));
	beanFactory.registerBeanDefinition("configClass2", new RootBeanDefinition(AStrich.class));
	new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory);
	try {
		beanFactory.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getMessage().contains("Circular reference"));
	}
}
 
Example #9
Source File: AutowiredAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testGenericsBasedConstructorInjectionWithNonTypedTarget() {
	RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class);
	bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", bd);
	GenericRepository gr = new GenericRepository();
	bf.registerSingleton("genericRepo", gr);

	RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
	assertSame(gr, bean.stringRepository);
	assertSame(gr, bean.integerRepository);
	assertSame(1, bean.stringRepositoryArray.length);
	assertSame(1, bean.integerRepositoryArray.length);
	assertSame(gr, bean.stringRepositoryArray[0]);
	assertSame(gr, bean.integerRepositoryArray[0]);
	assertSame(1, bean.stringRepositoryList.size());
	assertSame(1, bean.integerRepositoryList.size());
	assertSame(gr, bean.stringRepositoryList.get(0));
	assertSame(gr, bean.integerRepositoryList.get(0));
	assertSame(1, bean.stringRepositoryMap.size());
	assertSame(1, bean.integerRepositoryMap.size());
	assertSame(gr, bean.stringRepositoryMap.get("genericRepo"));
	assertSame(gr, bean.integerRepositoryMap.get("genericRepo"));
}
 
Example #10
Source File: PersistenceInjectionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublicExtendedPersistenceContextSetter() throws Exception {
	EntityManager mockEm = mock(EntityManager.class);
	given(mockEmf.createEntityManager()).willReturn(mockEm);

	GenericApplicationContext gac = new GenericApplicationContext();
	gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
	gac.registerBeanDefinition("annotationProcessor",
			new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
	gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
			new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
	gac.refresh();

	DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
			DefaultPublicPersistenceContextSetter.class.getName());
	assertNotNull(bean.em);
}
 
Example #11
Source File: PersistenceInjectionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testPublicExtendedPersistenceContextSetterWithEntityManagerInfoAndSerialization() throws Exception {
	EntityManager mockEm = mock(EntityManager.class, withSettings().serializable());
	given(mockEm.isOpen()).willReturn(true);
	EntityManagerFactoryWithInfo mockEmf = mock(EntityManagerFactoryWithInfo.class);
	given(mockEmf.getNativeEntityManagerFactory()).willReturn(mockEmf);
	given(mockEmf.getJpaDialect()).willReturn(new DefaultJpaDialect());
	given(mockEmf.getEntityManagerInterface()).willReturn((Class)EntityManager.class);
	given(mockEmf.getBeanClassLoader()).willReturn(getClass().getClassLoader());
	given(mockEmf.createEntityManager()).willReturn(mockEm);

	GenericApplicationContext gac = new GenericApplicationContext();
	gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
	gac.registerBeanDefinition("annotationProcessor",
			new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
	gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
			new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
	gac.refresh();

	DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
			DefaultPublicPersistenceContextSetter.class.getName());
	assertNotNull(bean.em);
	assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em));
}
 
Example #12
Source File: ResourcesBeanDefinitionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void registerUrlProvider(ParserContext context, @Nullable Object source) {
	if (!context.getRegistry().containsBeanDefinition(RESOURCE_URL_PROVIDER)) {
		RootBeanDefinition urlProvider = new RootBeanDefinition(ResourceUrlProvider.class);
		urlProvider.setSource(source);
		urlProvider.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		context.getRegistry().registerBeanDefinition(RESOURCE_URL_PROVIDER, urlProvider);
		context.registerComponent(new BeanComponentDefinition(urlProvider, RESOURCE_URL_PROVIDER));

		RootBeanDefinition interceptor = new RootBeanDefinition(ResourceUrlProviderExposingInterceptor.class);
		interceptor.setSource(source);
		interceptor.getConstructorArgumentValues().addIndexedArgumentValue(0, urlProvider);

		RootBeanDefinition mappedInterceptor = new RootBeanDefinition(MappedInterceptor.class);
		mappedInterceptor.setSource(source);
		mappedInterceptor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		mappedInterceptor.getConstructorArgumentValues().addIndexedArgumentValue(0, (Object) null);
		mappedInterceptor.getConstructorArgumentValues().addIndexedArgumentValue(1, interceptor);
		String mappedInterceptorName = context.getReaderContext().registerWithGeneratedName(mappedInterceptor);
		context.registerComponent(new BeanComponentDefinition(mappedInterceptor, mappedInterceptorName));
	}
}
 
Example #13
Source File: ConfigurationClassPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void genericsBasedInjection() {
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(beanFactory);
	beanFactory.addBeanPostProcessor(bpp);
	RootBeanDefinition bd = new RootBeanDefinition(RepositoryInjectionBean.class);
	bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	beanFactory.registerBeanDefinition("annotatedBean", bd);
	beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(RepositoryConfiguration.class));
	ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
	pp.postProcessBeanFactory(beanFactory);

	RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean");
	assertEquals("Repository<String>", bean.stringRepository.toString());
	assertEquals("Repository<Integer>", bean.integerRepository.toString());
}
 
Example #14
Source File: InjectAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectFactoryWithTypedListField() throws Exception {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryListFieldInjectionBean.class));
	bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
	bf.setSerializationId("test");

	ObjectFactoryListFieldInjectionBean bean = (ObjectFactoryListFieldInjectionBean) bf.getBean("annotatedBean");
	assertSame(bf.getBean("testBean"), bean.getTestBean());
	bean = (ObjectFactoryListFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
	assertSame(bf.getBean("testBean"), bean.getTestBean());
	bf.destroySingletons();
}
 
Example #15
Source File: CommonAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testLazyResolutionWithResourceField() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);

	bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(LazyResourceFieldInjectionBean.class));
	bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));

	LazyResourceFieldInjectionBean bean = (LazyResourceFieldInjectionBean) bf.getBean("annotatedBean");
	assertFalse(bf.containsSingleton("testBean"));
	bean.testBean.setName("notLazyAnymore");
	assertTrue(bf.containsSingleton("testBean"));
	TestBean tb = (TestBean) bf.getBean("testBean");
	assertEquals("notLazyAnymore", tb.getName());
}
 
Example #16
Source File: BusWiringBeanFactoryPostProcessor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Object getBusForName(String name,
                             ConfigurableListableBeanFactory factory,
                             boolean create,
                             String cn) {
    if (!factory.containsBeanDefinition(name) && (create || Bus.DEFAULT_BUS_ID.equals(name))) {
        DefaultListableBeanFactory df = (DefaultListableBeanFactory)factory;
        RootBeanDefinition rbd = new RootBeanDefinition(SpringBus.class);
        if (cn != null) {
            rbd.setAttribute("busConfig", new RuntimeBeanReference(cn));
        }
        df.registerBeanDefinition(name, rbd);
    } else if (cn != null) {
        BeanDefinition bd = factory.getBeanDefinition(name);
        bd.getPropertyValues().addPropertyValue("busConfig", new RuntimeBeanReference(cn));
    }
    return new RuntimeBeanReference(name);
}
 
Example #17
Source File: LazyAutowiredAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void doTestLazyResourceInjection(Class<? extends TestBeanHolder> annotatedBeanClass) {
	AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
	RootBeanDefinition abd = new RootBeanDefinition(annotatedBeanClass);
	abd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	ac.registerBeanDefinition("annotatedBean", abd);
	RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
	tbd.setLazyInit(true);
	ac.registerBeanDefinition("testBean", tbd);
	ac.refresh();

	TestBeanHolder bean = ac.getBean("annotatedBean", TestBeanHolder.class);
	assertFalse(ac.getBeanFactory().containsSingleton("testBean"));
	assertNotNull(bean.getTestBean());
	assertNull(bean.getTestBean().getName());
	assertTrue(ac.getBeanFactory().containsSingleton("testBean"));
	TestBean tb = (TestBean) ac.getBean("testBean");
	tb.setName("tb");
	assertSame("tb", bean.getTestBean().getName());
}
 
Example #18
Source File: ConfigurationClassPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void configurationClassesWithInvalidOverridingForProgrammaticCall() {
	beanFactory.registerBeanDefinition("config1", new RootBeanDefinition(InvalidOverridingSingletonBeanConfig.class));
	beanFactory.registerBeanDefinition("config2", new RootBeanDefinition(OverridingSingletonBeanConfig.class));
	beanFactory.registerBeanDefinition("config3", new RootBeanDefinition(SingletonBeanConfig.class));
	ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
	pp.postProcessBeanFactory(beanFactory);

	try {
		beanFactory.getBean(Bar.class);
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getMessage().contains("OverridingSingletonBeanConfig.foo"));
		assertTrue(ex.getMessage().contains(ExtendedFoo.class.getName()));
		assertTrue(ex.getMessage().contains(Foo.class.getName()));
		assertTrue(ex.getMessage().contains("InvalidOverridingSingletonBeanConfig"));
	}
}
 
Example #19
Source File: BeanValidationPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testNotNullConstraint() {
	GenericApplicationContext ac = new GenericApplicationContext();
	ac.registerBeanDefinition("bvpp", new RootBeanDefinition(BeanValidationPostProcessor.class));
	ac.registerBeanDefinition("capp", new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class));
	ac.registerBeanDefinition("bean", new RootBeanDefinition(NotNullConstrainedBean.class));
	try {
		ac.refresh();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getRootCause().getMessage().contains("testBean"));
		assertTrue(ex.getRootCause().getMessage().contains("invalid"));
	}
	ac.close();
}
 
Example #20
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testStaticPrototypeFactoryMethodFoundByNonEagerTypeMatching() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition rbd = new RootBeanDefinition(TestBeanFactory.class);
	rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	rbd.setFactoryMethodName("createTestBean");
	lbf.registerBeanDefinition("x1", rbd);

	TestBeanFactory.initialized = false;
	String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
	assertEquals(1, beanNames.length);
	assertEquals("x1", beanNames[0]);
	assertFalse(lbf.containsSingleton("x1"));
	assertTrue(lbf.containsBean("x1"));
	assertFalse(lbf.containsBean("&x1"));
	assertFalse(lbf.isSingleton("x1"));
	assertFalse(lbf.isSingleton("&x1"));
	assertTrue(lbf.isPrototype("x1"));
	assertFalse(lbf.isPrototype("&x1"));
	assertTrue(lbf.isTypeMatch("x1", TestBean.class));
	assertFalse(lbf.isTypeMatch("&x1", TestBean.class));
	assertEquals(TestBean.class, lbf.getType("x1"));
	assertEquals(null, lbf.getType("&x1"));
	assertFalse(TestBeanFactory.initialized);
}
 
Example #21
Source File: JdkProxyControllerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerclass) throws ServletException {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			wac.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor(true)));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example #22
Source File: AutowiredAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testResourceInjection() {
	RootBeanDefinition bd = new RootBeanDefinition(ResourceInjectionBean.class);
	bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", bd);
	TestBean tb = new TestBean();
	bf.registerSingleton("testBean", tb);

	ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb, bean.getTestBean());
	assertSame(tb, bean.getTestBean2());

	bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb, bean.getTestBean());
	assertSame(tb, bean.getTestBean2());
}
 
Example #23
Source File: AutowiredAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testConstructorResourceInjection() {
	RootBeanDefinition bd = new RootBeanDefinition(ConstructorResourceInjectionBean.class);
	bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", bd);
	TestBean tb = new TestBean();
	bf.registerSingleton("testBean", tb);
	NestedTestBean ntb = new NestedTestBean();
	bf.registerSingleton("nestedTestBean", ntb);

	ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb, bean.getTestBean());
	assertSame(tb, bean.getTestBean2());
	assertSame(tb, bean.getTestBean3());
	assertSame(tb, bean.getTestBean4());
	assertSame(ntb, bean.getNestedTestBean());
	assertSame(bf, bean.getBeanFactory());

	bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb, bean.getTestBean());
	assertSame(tb, bean.getTestBean2());
	assertSame(tb, bean.getTestBean3());
	assertSame(tb, bean.getTestBean4());
	assertSame(ntb, bean.getNestedTestBean());
	assertSame(bf, bean.getBeanFactory());
}
 
Example #24
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void responseBodyAsHtmlWithProducesCondition() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			ContentNegotiationManagerFactoryBean factoryBean = new ContentNegotiationManagerFactoryBean();
			factoryBean.afterPropertiesSet();
			RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
			adapterDef.getPropertyValues().add("contentNegotiationManager", factoryBean.getObject());
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
		}
	}, TextRestController.class);

	byte[] content = "alert('boo')".getBytes(Charset.forName("ISO-8859-1"));
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/a3.html");
	request.setContent(content);
	MockHttpServletResponse response = new MockHttpServletResponse();

	getServlet().service(request, response);

	assertEquals(200, response.getStatus());
	assertEquals("text/html", response.getContentType());
	assertNull(response.getHeader("Content-Disposition"));
	assertArrayEquals(content, response.getContentAsByteArray());
}
 
Example #25
Source File: FormattingConversionServiceTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void testFormatFieldForAnnotationWithPlaceholdersAndFactoryBean() throws Exception {
	GenericApplicationContext context = new GenericApplicationContext();
	PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
	Properties props = new Properties();
	props.setProperty("dateStyle", "S-");
	props.setProperty("datePattern", "M-d-yy");
	ppc.setProperties(props);
	context.registerBeanDefinition("formattingService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
	context.getBeanFactory().registerSingleton("ppc", ppc);
	context.refresh();
	formattingService = context.getBean("formattingService", FormattingConversionService.class);
	doTestFormatFieldForAnnotation(ModelWithPlaceholders.class, false);
}
 
Example #26
Source File: AutowiredConfigurationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * {@link Autowired} constructors are not supported on {@link Configuration} classes
 * due to CGLIB constraints
 */
@Test(expected = BeanCreationException.class)
public void testAutowiredConfigurationConstructorsAreNotSupported() {
	DefaultListableBeanFactory context = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(context).loadBeanDefinitions(
			new ClassPathResource("annotation-config.xml", AutowiredConstructorConfig.class));
	GenericApplicationContext ctx = new GenericApplicationContext(context);
	ctx.registerBeanDefinition("config1", new RootBeanDefinition(AutowiredConstructorConfig.class));
	ctx.registerBeanDefinition("config2", new RootBeanDefinition(ColorConfig.class));
	ctx.refresh(); // should throw
}
 
Example #27
Source File: InjectAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testOptionalListFieldInjectionWithBeanAvailable() {
	bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListFieldInjectionBean.class));
	bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));

	OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean");
	assertTrue(bean.getTestBean().isPresent());
	assertSame(bf.getBean("testBean"), bean.getTestBean().get().get(0));
}
 
Example #28
Source File: AutowiredAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testMethodInjectionWithMapAndNoMatches() {
	bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));

	MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
	assertNull(bean.getTestBeanMap());
	assertNull(bean.getTestBean());
}
 
Example #29
Source File: AnnotationInjectedBeanPostProcessor.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
    if (beanType != null) {
        InjectionMetadata metadata = findInjectionMetadata(beanName, beanType, null);
        metadata.checkConfigMembers(beanDefinition);
    }
}
 
Example #30
Source File: AutowiredAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtendedResourceInjection() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerResolvableDependency(BeanFactory.class, bf);
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	RootBeanDefinition bd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
	bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", bd);
	TestBean tb = new TestBean();
	bf.registerSingleton("testBean", tb);
	NestedTestBean ntb = new NestedTestBean();
	bf.registerSingleton("nestedTestBean", ntb);

	TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb, bean.getTestBean());
	assertSame(tb, bean.getTestBean2());
	assertSame(tb, bean.getTestBean3());
	assertSame(tb, bean.getTestBean4());
	assertSame(ntb, bean.getNestedTestBean());
	assertSame(bf, bean.getBeanFactory());

	bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb, bean.getTestBean());
	assertSame(tb, bean.getTestBean2());
	assertSame(tb, bean.getTestBean3());
	assertSame(tb, bean.getTestBean4());
	assertSame(ntb, bean.getNestedTestBean());
	assertSame(bf, bean.getBeanFactory());

	String[] depBeans = bf.getDependenciesForBean("annotatedBean");
	assertEquals(2, depBeans.length);
	assertEquals("testBean", depBeans[0]);
	assertEquals("nestedTestBean", depBeans[1]);
}