List of usage examples for org.springframework.context.support GenericApplicationContext getBean
@Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException
From source file:com.opengamma.component.factory.AbstractSpringComponentFactory.java
/** * Registers a set of beans by type.//w w w. j a v a 2s . c om * * @param <T> the type * @param repo the repository to register in, not null * @param type the type of bean to extract from the Spring context, not null * @param appContext the Spring context, not null */ protected <T> void registerInfrastructureByType(ComponentRepository repo, Class<T> type, GenericApplicationContext appContext) { String[] beanNames = appContext.getBeanNamesForType(type); for (String beanName : beanNames) { T bean = appContext.getBean(beanName, type); String name = simplifyName(type, beanName); repo.registerComponent(type, name, bean); String[] aliases = appContext.getAliases(beanName); for (String alias : aliases) { name = simplifyName(type, alias); repo.registerComponent(type, name, bean); } } }
From source file:org.springframework.cloud.aws.context.config.xml.ContextCredentialsBeanDefinitionParserTest.java
@Test public void parseBean_withProfileCredentialsProviderAndProfileFile_createProfileCredentialsProvider() throws IOException { GenericApplicationContext applicationContext = new GenericApplicationContext(); Map<String, Object> secretAndAccessKeyMap = new HashMap<>(); secretAndAccessKeyMap.put("profilePath", new ClassPathResource(getClass().getSimpleName() + "-profile", getClass()).getFile() .getAbsolutePath()); applicationContext.getEnvironment().getPropertySources() .addLast(new MapPropertySource("test", secretAndAccessKeyMap)); PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); configurer.setPropertySources(applicationContext.getEnvironment().getPropertySources()); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(applicationContext); reader.loadBeanDefinitions(new ClassPathResource( getClass().getSimpleName() + "-profileCredentialsProviderWithFile.xml", getClass())); applicationContext.refresh();// www. j a va 2 s .c om AWSCredentialsProvider provider = applicationContext.getBean( AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME, AWSCredentialsProvider.class); assertNotNull(provider); assertEquals("testAccessKey", provider.getCredentials().getAWSAccessKeyId()); assertEquals("testSecretKey", provider.getCredentials().getAWSSecretKey()); }
From source file:com.google.code.guice.repository.configuration.JpaRepositoryModule.java
/** * Creates Spring application context based on found persistence units. Context will be initialized with multiple * persistence units support.//from w w w . j ava 2 s . c o m * * @param configurationManager configuration manager with persistence units configurations. * * @return initialized Spring context * * @see <a href="https://github.com/SpringSource/spring-data-jpa/blob/master/src/test/resources/multiple-entity-manager-integration-context.xml"/> */ protected ApplicationContext createApplicationContext( PersistenceUnitsConfigurationManager configurationManager) { GenericApplicationContext context = new GenericApplicationContext(); String abstractEMFBeanName = "abstractEntityManagerFactory"; context.registerBeanDefinition(abstractEMFBeanName, BeanDefinitionBuilder.genericBeanDefinition(LocalContainerEntityManagerFactoryBean.class) .setAbstract(true).getBeanDefinition()); Iterable<PersistenceUnitConfiguration> configurations = configurationManager.getConfigurations(); for (PersistenceUnitConfiguration configuration : configurations) { String persistenceUnitName = configuration.getPersistenceUnitName(); logger.info(String.format("Processing persistence unit: [%s]", persistenceUnitName)); Map props = configuration.getProperties(); String entityManagerFactoryName = "entityManagerFactory#" + persistenceUnitName; BeanDefinitionBuilder emfFactoryDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition() .setParentName(abstractEMFBeanName).addPropertyValue("persistenceUnitName", persistenceUnitName) .addPropertyValue("jpaProperties", props); // Additional EntityManagerFactory properties for Spring EMFBean initialization - s.a. jpaDialect, jpaVendorAdapter Map<String, Object> properties = getAdditionalEMFProperties(persistenceUnitName); if (properties != null) { for (String propertyName : properties.keySet()) { Object value = properties.get(propertyName); if (value != null) { logger.info( String.format("Found additional EMF property: [%s] -> [%s]", propertyName, value)); emfFactoryDefinitionBuilder.addPropertyValue(propertyName, value); } } } context.registerBeanDefinition(entityManagerFactoryName, emfFactoryDefinitionBuilder.getBeanDefinition()); // Naming is important - it's needed for later TransactionManager resolution based on @Transactional value with persistenceUnitName context.registerBeanDefinition(persistenceUnitName, BeanDefinitionBuilder.genericBeanDefinition(JpaTransactionManager.class) .addPropertyReference("entityManagerFactory", entityManagerFactoryName) .getBeanDefinition()); PlatformTransactionManager transactionManager = context.getBean(persistenceUnitName, PlatformTransactionManager.class); TransactionInterceptor transactionInterceptor = new TransactionInterceptor(transactionManager, createTransactionAttributeSource()); transactionInterceptor.setBeanFactory(context); // Wiring components EntityManagerFactory emf = context.getBean(entityManagerFactoryName, EntityManagerFactory.class); EntityManager entityManager = SharedEntityManagerCreator.createSharedEntityManager(emf, props); configuration.setEntityManager(entityManager); configuration.setEntityManagerFactory(emf); configuration.setTransactionManager(transactionManager); configuration.setTransactionManagerName(persistenceUnitName); configuration.setTransactionInterceptor(transactionInterceptor); // Default bindings for EMF & Transaction Manager - they needed for repositories with @Transactional without value if (configuration.isDefault()) { context.registerAlias(entityManagerFactoryName, "entityManagerFactory"); context.registerAlias(persistenceUnitName, "transactionManager"); } } return context; }
From source file:org.springframework.context.expression.ApplicationContextExpressionTests.java
@Test public void genericApplicationContext() throws Exception { GenericApplicationContext ac = new GenericApplicationContext(); AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); ac.getBeanFactory().registerScope("myScope", new Scope() { @Override/*from w ww. j a va 2 s .c om*/ public Object get(String name, ObjectFactory<?> objectFactory) { return objectFactory.getObject(); } @Override public Object remove(String name) { return null; } @Override public void registerDestructionCallback(String name, Runnable callback) { } @Override public Object resolveContextualObject(String key) { if (key.equals("mySpecialAttr")) { return "42"; } else { return null; } } @Override public String getConversationId() { return null; } }); PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); Properties placeholders = new Properties(); placeholders.setProperty("code", "123"); ppc.setProperties(placeholders); ac.addBeanFactoryPostProcessor(ppc); GenericBeanDefinition bd0 = new GenericBeanDefinition(); bd0.setBeanClass(TestBean.class); bd0.getPropertyValues().add("name", "myName"); bd0.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "original")); ac.registerBeanDefinition("tb0", bd0); GenericBeanDefinition bd1 = new GenericBeanDefinition(); bd1.setBeanClassName("#{tb0.class}"); bd1.setScope("myScope"); bd1.getConstructorArgumentValues().addGenericArgumentValue("XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ"); bd1.getConstructorArgumentValues().addGenericArgumentValue("#{mySpecialAttr}"); ac.registerBeanDefinition("tb1", bd1); GenericBeanDefinition bd2 = new GenericBeanDefinition(); bd2.setBeanClassName("#{tb1.class.name}"); bd2.setScope("myScope"); bd2.getPropertyValues().add("name", "{ XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ }"); bd2.getPropertyValues().add("age", "#{mySpecialAttr}"); bd2.getPropertyValues().add("country", "${code} #{systemProperties.country}"); ac.registerBeanDefinition("tb2", bd2); GenericBeanDefinition bd3 = new GenericBeanDefinition(); bd3.setBeanClass(ValueTestBean.class); bd3.setScope("myScope"); ac.registerBeanDefinition("tb3", bd3); GenericBeanDefinition bd4 = new GenericBeanDefinition(); bd4.setBeanClass(ConstructorValueTestBean.class); bd4.setScope("myScope"); ac.registerBeanDefinition("tb4", bd4); GenericBeanDefinition bd5 = new GenericBeanDefinition(); bd5.setBeanClass(MethodValueTestBean.class); bd5.setScope("myScope"); ac.registerBeanDefinition("tb5", bd5); GenericBeanDefinition bd6 = new GenericBeanDefinition(); bd6.setBeanClass(PropertyValueTestBean.class); bd6.setScope("myScope"); ac.registerBeanDefinition("tb6", bd6); System.getProperties().put("country", "UK"); try { ac.refresh(); TestBean tb0 = ac.getBean("tb0", TestBean.class); TestBean tb1 = ac.getBean("tb1", TestBean.class); assertEquals("XXXmyNameYYY42ZZZ", tb1.getName()); assertEquals(42, tb1.getAge()); TestBean tb2 = ac.getBean("tb2", TestBean.class); assertEquals("{ XXXmyNameYYY42ZZZ }", tb2.getName()); assertEquals(42, tb2.getAge()); assertEquals("123 UK", tb2.getCountry()); ValueTestBean tb3 = ac.getBean("tb3", ValueTestBean.class); assertEquals("XXXmyNameYYY42ZZZ", tb3.name); assertEquals(42, tb3.age); assertEquals(42, tb3.ageFactory.getObject().intValue()); assertEquals("123 UK", tb3.country); assertEquals("123 UK", tb3.countryFactory.getObject()); System.getProperties().put("country", "US"); assertEquals("123 UK", tb3.country); assertEquals("123 US", tb3.countryFactory.getObject()); System.getProperties().put("country", "UK"); assertEquals("123 UK", tb3.country); assertEquals("123 UK", tb3.countryFactory.getObject()); assertSame(tb0, tb3.tb); tb3 = (ValueTestBean) SerializationTestUtils.serializeAndDeserialize(tb3); assertEquals("123 UK", tb3.countryFactory.getObject()); ConstructorValueTestBean tb4 = ac.getBean("tb4", ConstructorValueTestBean.class); assertEquals("XXXmyNameYYY42ZZZ", tb4.name); assertEquals(42, tb4.age); assertEquals("123 UK", tb4.country); assertSame(tb0, tb4.tb); MethodValueTestBean tb5 = ac.getBean("tb5", MethodValueTestBean.class); assertEquals("XXXmyNameYYY42ZZZ", tb5.name); assertEquals(42, tb5.age); assertEquals("123 UK", tb5.country); assertSame(tb0, tb5.tb); PropertyValueTestBean tb6 = ac.getBean("tb6", PropertyValueTestBean.class); assertEquals("XXXmyNameYYY42ZZZ", tb6.name); assertEquals(42, tb6.age); assertEquals("123 UK", tb6.country); assertSame(tb0, tb6.tb); } finally { System.getProperties().remove("country"); } }
From source file:org.springframework.context.expression.ApplicationContextExpressionTests.java
@Test public void systemPropertiesSecurityManager() { GenericApplicationContext ac = new GenericApplicationContext(); AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); GenericBeanDefinition bd = new GenericBeanDefinition(); bd.setBeanClass(TestBean.class); bd.getPropertyValues().add("country", "#{systemProperties.country}"); ac.registerBeanDefinition("tb", bd); SecurityManager oldSecurityManager = System.getSecurityManager(); try {/* w ww .java 2 s . c o m*/ System.setProperty("country", "NL"); SecurityManager securityManager = new SecurityManager() { @Override public void checkPropertiesAccess() { throw new AccessControlException("Not Allowed"); } @Override public void checkPermission(Permission perm) { // allow everything else } }; System.setSecurityManager(securityManager); ac.refresh(); TestBean tb = ac.getBean("tb", TestBean.class); assertEquals("NL", tb.getCountry()); } finally { System.setSecurityManager(oldSecurityManager); System.getProperties().remove("country"); } }
From source file:org.springframework.context.expression.ApplicationContextExpressionTests.java
@Test public void stringConcatenationWithDebugLogging() { GenericApplicationContext ac = new GenericApplicationContext(); AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); GenericBeanDefinition bd = new GenericBeanDefinition(); bd.setBeanClass(String.class); bd.getConstructorArgumentValues()/*from www . j a v a 2s . co m*/ .addGenericArgumentValue("test-#{ T(java.lang.System).currentTimeMillis() }"); ac.registerBeanDefinition("str", bd); ac.refresh(); String str = ac.getBean("str", String.class); assertTrue(str.startsWith("test-")); }