public void init(ServletConfig config) throws ServletException { try { WebApplicationContext springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()); final AutowireCapableBeanFactory beanFactory = springContext.getAutowireCapableBeanFactory(); beanFactory.autowireBean(this); } catch (Exception e) { logger.error("Error initializing ShibbolethExtAuthnHandler", e); } }
public static Map<String, CommandHandler> buildCommandHandlersRegistry(final String basePackage, final ApplicationContext context) { final Map<String, CommandHandler> registry = new HashMap<>(); final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory(); scanner.addIncludeFilter(new AssignableTypeFilter(CommandHandler.class)); CommandHandler currentHandler = null; for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) { currentHandler = (CommandHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()), AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); registry.put(currentHandler.getInterest(), currentHandler); } return registry; }
@Test public void testAutowireWithSatisfiedJavaBeanDependency() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "Rod"); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); lbf.registerBeanDefinition("rod", bd); assertEquals(1, lbf.getBeanDefinitionCount()); // Depends on age, name and spouse (TestBean) Object registered = lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); assertEquals(1, lbf.getBeanDefinitionCount()); DependenciesBean kerry = (DependenciesBean) registered; TestBean rod = (TestBean) lbf.getBean("rod"); assertSame(rod, kerry.getSpouse()); }
@Test public void testAutowireWithTwoMatchesForConstructorDependency() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("rod", bd); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("rod2", bd2); try { lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertTrue(ex.getMessage().contains("rod")); assertTrue(ex.getMessage().contains("rod2")); } }
@Test public void testAutowireWithUnsatisfiedConstructorDependency() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("name", "Rod")); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); lbf.registerBeanDefinition("rod", bd); assertEquals(1, lbf.getBeanDefinitionCount()); try { lbf.autowire(UnsatisfiedConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true); fail("Should have unsatisfied constructor dependency on SideEffectBean"); } catch (UnsatisfiedDependencyException ex) { // expected } }
@Test public void testAutowireBeanByTypeWithTwoMatches() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); try { lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertTrue(ex.getMessage().contains("test")); assertTrue(ex.getMessage().contains("spouse")); } }
@Test public void testAutowireBeanByTypeWithTwoMatchesAndParameterNameDiscovery() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); try { lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertTrue(ex.getMessage().contains("test")); assertTrue(ex.getMessage().contains("spouse")); } }
@Test public void testAutowireBeanByTypeWithTwoPrimaryCandidates() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPrimary(true); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); bd2.setPrimary(true); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); try { lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertNotNull("Exception should have cause", ex.getCause()); assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass()); } }
@Test public void testAutowireBeanByTypeWithIdenticalPriorityCandidates() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); lbf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); RootBeanDefinition bd = new RootBeanDefinition(HighPriorityTestBean.class); RootBeanDefinition bd2 = new RootBeanDefinition(HighPriorityTestBean.class); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); try { lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertNotNull("Exception should have cause", ex.getCause()); assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass()); assertTrue(ex.getMessage().contains("5")); // conflicting priority } }
public LdapUserManager getInstance(final LdapUserManager.Provider provider) { LdapUserManager ldapUserManager; if (provider == LdapUserManager.Provider.MICROSOFTAD) { ldapUserManager = ldapUserManagerMap.get(LdapUserManager.Provider.MICROSOFTAD); if (ldapUserManager == null) { ldapUserManager = new ADLdapUserManagerImpl(); applicationCtx.getAutowireCapableBeanFactory().autowireBeanProperties(ldapUserManager, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); ldapUserManagerMap.put(LdapUserManager.Provider.MICROSOFTAD, ldapUserManager); } } else { //defaults to openldap ldapUserManager = ldapUserManagerMap.get(LdapUserManager.Provider.OPENLDAP); if (ldapUserManager == null) { ldapUserManager = new OpenLdapUserManagerImpl(); applicationCtx.getAutowireCapableBeanFactory().autowireBeanProperties(ldapUserManager, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); ldapUserManagerMap.put(LdapUserManager.Provider.OPENLDAP, ldapUserManager); } } return ldapUserManager; }
public static Map<String, CommandHandler> buildCommandHandlersRegistry(final String basePackage, final ApplicationContext context) { final Map<String, CommandHandler> registry = new HashMap<>(); final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory(); scanner.addIncludeFilter(new AssignableTypeFilter(CommandHandler.class)); CommandHandler currentHandler = null; for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) { currentHandler = (CommandHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()), AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); registry.put(currentHandler.getInterest().getName(), currentHandler); } return registry; }
public static Map<String, EventHandler> buildEventHandlersRegistry(final String basePackage, final ApplicationContext context) { final Map<String, EventHandler> registry = new HashMap<>(); final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory(); scanner.addIncludeFilter(new AssignableTypeFilter(EventHandler.class)); EventHandler currentHandler = null; for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) { currentHandler = (EventHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()), AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); registry.put(currentHandler.getInterest(), currentHandler); } return registry; }
private void installGenerator(final URI pluginId, final Version version, final PluginVO plugin, final ClassPathXmlApplicationContext cax, final Generator<GeneratorConfiguration, GeneratorStatistics> generator) { cax.getAutowireCapableBeanFactory() .autowireBeanProperties(generator, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); if (generator.getConfiguration() == null) { GeneratorConfiguration generatorConfiguration = generator.newConfiguration(); generator.setConfiguration(generatorConfiguration); } if (LifecyclePhase.NOT_INSTALLED.toString().equals(plugin.getState())) generator.install(true); else generator.install(false); pluginDAO.updatePluginState(pluginId, version, LifecyclePhase.INSTALLED.toString()); generator.initialize(); generators.put(generator.getId(), generator); contexts.put(generator.getId(), cax); logger.info("registered plugin " + generator.getSourceType()); pluginDAO.updatePluginState(pluginId, version, LifecyclePhase.INITIALIZED.toString()); }
private synchronized Object doGet(final String className) { // Check again for the cache here, inside the sync method Object bean = beans.get(className); if (bean != null) { return bean; } try { AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory(); Class<?> beanClass = Class.forName(className); bean = factory.createBean(beanClass, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); factory.initializeBean(bean, beanClass.getSimpleName() + "#" + System.identityHashCode(bean)); beans.put(className, bean); return bean; } catch (Exception e) { throw new IllegalArgumentException("Couldn't instantiate class " + className, e); } }
@Override public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); String webPropertyId = getWebPropertyId(); if (webPropertyId == null) { ServletContext sc = ((PageContext) getJspContext()).getServletContext(); ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc); context.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); } if (webPropertyId.equals("UA-XXXXXXX-X")) { LOG.warn("googleAnalytics.webPropertyId has not been overridden in a custom property file. Please set this in order to properly use the Google Analytics tag"); } out.println(analytics(webPropertyId, order)); super.doTag(); }
private void autowireArguments(Object service, Object[] args) { if (disableAutowiredArguments) { return; } if (args == null) { return; } if (shouldAutowire(service)) { for (Object arg : args) { if (arg == null) { continue; } AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); beanFactory.autowireBeanProperties(arg, AutowireCapableBeanFactory.AUTOWIRE_NO, false); beanFactory.initializeBean(arg, arg.getClass().getName()); } } }
private void autowireAndInitialize(ServletRequest req, Map<String, Object> contexts) { ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(req.getServletContext()); AutowireCapableBeanFactory autowirer = appContext.getAutowireCapableBeanFactory(); for (Map.Entry<String,Object> entry : contexts.entrySet()) { Object context = entry.getValue(); autowirer.autowireBean(context); try { if (context instanceof InitializingBean) { ((InitializingBean) context).afterPropertiesSet(); } } catch (Exception e) { logger.warn("Invocation of init method failed of context: " + entry.getKey(), e); } } }
/** * 初始化类资源的存储空间 * @param clz 类实例 * @return */ private Storage initializeStorage(Class clz) { ResourceDefinition definition = this.definitions.get(clz); if (definition == null) { FormattingTuple message = MessageFormatter.format("静态资源[{}]的信息定义不存在,可能是配置缺失", clz.getSimpleName()); logger.error(message.getMessage()); throw new IllegalStateException(message.getMessage()); } AutowireCapableBeanFactory beanFactory = this.applicationContext.getAutowireCapableBeanFactory(); Storage storage = beanFactory.createBean(Storage.class); Storage prev = storages.putIfAbsent(clz, storage); if (prev == null) { storage.initialize(definition); } return prev == null ? storage : prev; }
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContextEvent.getServletContext()); AutowireCapableBeanFactory autowireCapableBeanFactory=webApplicationContext.getAutowireCapableBeanFactory(); autowireCapableBeanFactory.autowireBean(this); //Permitirmos varias "locations" en el parámetro separados por "\n" String[] rawLocations = (servletContextEvent.getServletContext().getInitParameter("databasemigration.location")+"").split("\\n"); List<String> locations = new ArrayList<String>(); for(String location : rawLocations) { if ((location!=null) && (location.trim().isEmpty()==false)) { locations.add(location); } } databaseMigration.migrate(locations); }
@Test public void testAutowireWithTwoMatchesForConstructorDependency() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("rod", bd); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("rod2", bd2); try { lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertTrue(ex.getMessage().indexOf("rod") != -1); assertTrue(ex.getMessage().indexOf("rod2") != -1); } }
@Test public void testAutowireBeanByTypeWithTwoMatches() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); try { lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertTrue(ex.getMessage().indexOf("test") != -1); assertTrue(ex.getMessage().indexOf("spouse") != -1); } }
@Test public void testAutowireBeanByTypeWithTwoMatchesAndParameterNameDiscovery() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); try { lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertTrue(ex.getMessage().indexOf("test") != -1); assertTrue(ex.getMessage().indexOf("spouse") != -1); } }
@Override public void init(FilterConfig filterConfig) throws ServletException { String module = filterConfig.getInitParameter("module"); CloudStackSpringContext context = (CloudStackSpringContext)filterConfig.getServletContext().getAttribute(CloudStackSpringContext.CLOUDSTACK_CONTEXT_SERVLET_KEY); if (context == null) return; ApplicationContext applicationContext = context.getApplicationContextForWeb(module); if (applicationContext != null) { AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory(); if (factory != null) { factory.autowireBean(this); enabled = true; } } }
public LdapUserManager getInstance(LdapUserManager.Provider provider) { LdapUserManager ldapUserManager; if (provider == LdapUserManager.Provider.MICROSOFTAD) { ldapUserManager = ldapUserManagerMap.get(LdapUserManager.Provider.MICROSOFTAD); if (ldapUserManager == null) { ldapUserManager = new ADLdapUserManagerImpl(); applicationCtx.getAutowireCapableBeanFactory().autowireBeanProperties(ldapUserManager, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); ldapUserManagerMap.put(LdapUserManager.Provider.MICROSOFTAD, ldapUserManager); } } else { //defaults to openldap ldapUserManager = ldapUserManagerMap.get(LdapUserManager.Provider.OPENLDAP); if (ldapUserManager == null) { ldapUserManager = new OpenLdapUserManagerImpl(); applicationCtx.getAutowireCapableBeanFactory().autowireBeanProperties(ldapUserManager, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); ldapUserManagerMap.put(LdapUserManager.Provider.OPENLDAP, ldapUserManager); } } return ldapUserManager; }
protected static void preInit(final String... additionalContextFiles) { TimeZone.setDefault(DateHelper.UTC); log.info("user.timezone is: " + System.getProperty("user.timezone")); TestConfiguration.initAsTestConfiguration(additionalContextFiles); testConfiguration = TestConfiguration.getConfiguration(); final DaoRegistry daoRegistry = TestConfiguration.getConfiguration().getBean("daoRegistry", DaoRegistry.class); daoRegistry.init(); initTestDB = testConfiguration.getBean("initTestDB", InitTestDB.class); testConfiguration.autowire(initTestDB, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME); final File testDir = new File(TEST_DIR); if (testDir.exists() == false) { testDir.mkdir(); } if (DatabaseSupport.getInstance() == null) { DatabaseSupport.setInstance(new DatabaseSupport(HibernateUtils.getDialect())); } }
@BeforeMethod public void beforeMethod() throws IOException, OWLOntologyCreationException, NoSuchMethodException { // ontology repository collection is not spring managed, see FileRepositoryCollectionFactory File file = ResourceUtils.getFile("small_test_data_NGtest.owl.zip"); OntologyRepositoryCollection ontologyRepoCollection = BeanUtils.instantiateClass( OntologyRepositoryCollection.class.getConstructor(File.class), file); autowireCapableBeanFactory.autowireBeanProperties(ontologyRepoCollection, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); ontologyRepoCollection.init(); ontologyRepository = ontologyRepoCollection.getRepository(ONTOLOGY); ontologyTermDynamicAnnotationRepository = ontologyRepoCollection.getRepository( ONTOLOGY_TERM_DYNAMIC_ANNOTATION); ontologyTermNodePathRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM_NODE_PATH); ontologyTermSynonymRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM_SYNONYM); ontologyTermRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM); }
/** * Creates an instance of the bean. * * @return the created instance * * @throws Exception * if the instance cannot be created */ protected Object createInstance() throws Exception { final Constructor<?> constructor = findMatchingConstructor(); final Object object = constructor.newInstance(constArgs); // check if we have to apply properties if (properties != null && properties.size() > 0) { new BeanWrapperImpl(object).setPropertyValues(values); } // auto-wire everything if the factory supports that if (beanFactory instanceof AutowireCapableBeanFactory) { ((AutowireCapableBeanFactory) beanFactory).autowireBeanProperties( object, AutowireCapableBeanFactory.AUTOWIRE_NO, false); } return object; }
@PostConstruct public void registerWithServer() { AutowireCapableBeanFactory factory = context .getAutowireCapableBeanFactory(); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory; GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(RmiServiceExporter.class); beanDefinition.setAutowireCandidate(true); MutablePropertyValues propertyValues = new MutablePropertyValues(); Class<?> serviceInterface = this.getClass().getInterfaces()[0]; propertyValues.addPropertyValue("serviceInterface", serviceInterface); String serviceName = serviceInterface.getCanonicalName(); propertyValues.addPropertyValue("serviceName", serviceName); propertyValues.addPropertyValue("service", this); propertyValues.addPropertyValue("registryPort", "1099"); beanDefinition.setPropertyValues(propertyValues); registry.registerBeanDefinition(serviceName, beanDefinition); context.getBean(serviceName); // Need this else // NotBoundException getService().registerClient(getHostAddress()); }
@Override protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); final Object job = super.createJobInstance(bundle); logger.debug("Created job {} for bundle {}", job, bundle); beanFactory.autowireBean(job); logger.debug("Autowired job per the application context"); return job; }
public static void registerSingleton(ApplicationContext applicationContext, String beanName, Object singletonObject) { AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); if (!SingletonBeanRegistry.class.isAssignableFrom(beanFactory.getClass())) { throw new IllegalArgumentException( "ApplicationContext: " + applicationContext.getClass().toString() + " doesn't implements SingletonBeanRegistry, cannot register JMS connection at runtime"); } SingletonBeanRegistry beanDefinitionRegistry = (SingletonBeanRegistry) beanFactory; beanDefinitionRegistry.registerSingleton(beanName, singletonObject); }
@Bean EventManager getEventManger( AutowireCapableBeanFactory beanFactory, @Value("${martini.event.manager.impl:#{null}}") Class<? extends EventManager> implementation ) { return null == implementation ? beanFactory.createBean(DefaultEventManager.class) : beanFactory.createBean(implementation); }
@Bean MartiniResultMarshaller getMartiniResultMarshaller( AutowireCapableBeanFactory beanFactory, @Value("${martini.result.marshaller.implementation:#{null}}") Class<? extends MartiniResultMarshaller> implementation ) { return null == implementation ? beanFactory.createBean(DefaultMartiniResultMarshaller.class) : beanFactory.createBean(implementation); }