Example usage for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_NAME

List of usage examples for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_NAME

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_NAME.

Prototype

int AUTOWIRE_BY_NAME

To view the source code for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_NAME.

Click Source Link

Document

Constant that indicates autowiring bean properties by name (applying to all bean property setters).

Usage

From source file:org.grails.datastore.gorm.jpa.EntityInterceptorInvokingEntityListener.java

@PostLoad
public void postLoad(final Object o) {
    doWithSession(o, new JpaSessionTemplate() {
        public void doWithSession(final JpaSession session, final PersistentEntity entity,
                final EntityAccess ea) {

            session.getDatastore().getApplicationContext().getAutowireCapableBeanFactory()
                    .autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

            PostLoadEvent event = new PostLoadEvent(session.getDatastore(), entity, ea);
            event.addExcludedListenerName(DomainEventListener.class.getName());
            session.getDatastore().getApplicationEventPublisher().publishEvent(event);
        }/*  w w w  . j a v a2  s  .co  m*/
    });
}

From source file:org.springmodules.validation.valang.parser.DefaultVisitor.java

private Function lifeCycleCallbacks(Function function, int line, int column) {
    if (function instanceof BeanFactoryAware) {
        ((BeanFactoryAware) function).setBeanFactory(beanFactory);
    }//from  w ww .  j  a  v  a2  s . c o  m
    if (function instanceof ApplicationContextAware) {
        ((ApplicationContextAware) function).setApplicationContext(applicationContext);
    }
    if (function instanceof ResourceLoaderAware) {
        ((ResourceLoaderAware) function).setResourceLoader(resourceLoader);
    }
    if (function instanceof MessageSourceAware) {
        ((MessageSourceAware) function).setMessageSource(messageSource);
    }
    if (function instanceof ApplicationEventPublisherAware) {
        ((ApplicationEventPublisherAware) function).setApplicationEventPublisher(applicationEventPublisher);
    }
    if (function instanceof ServletContextAware) {
        ((ServletContextAware) function).setServletContext(servletContext);
    }
    if (function instanceof AbstractFunction) {
        AbstractFunction abstractFunction = (AbstractFunction) function;
        AutowireCapableBeanFactory autowireCapableBeanFactory = null;

        if (abstractFunction.isAutowireByName() || abstractFunction.isAutowireByType()) {
            if (applicationContext instanceof ConfigurableApplicationContext) {
                ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
                autowireCapableBeanFactory = configurableApplicationContext.getBeanFactory();
            } else if (beanFactory instanceof AutowireCapableBeanFactory) {
                autowireCapableBeanFactory = (AutowireCapableBeanFactory) beanFactory;
            } else if (applicationContext == null && beanFactory == null) {
                throw new ValangException(
                        "Could not autowire function: no application context or bean factory available", line,
                        column);
            } else {
                throw new ValangException(
                        "Could not autowire function: application context or bean factory does not support autowiring",
                        line, column);
            }
        }
        if (abstractFunction.isAutowireByName()) {
            autowireCapableBeanFactory.autowireBeanProperties(function,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
        }
        if (abstractFunction.isAutowireByType()) {
            autowireCapableBeanFactory.autowireBeanProperties(function,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
        }
        try {
            abstractFunction.init();
        } catch (Exception e) {
            throw new ValangException("Error initializing function", e, line, column);
        }
    }
    return function;
}

From source file:de.hybris.platform.btgcockpit.service.BTGCockpitServiceTest.java

public void initApplicationContext() {
    final GenericApplicationContext context = new GenericApplicationContext();
    context.setResourceLoader(new DefaultResourceLoader(Registry.class.getClassLoader()));
    context.setClassLoader(Registry.class.getClassLoader());
    context.getBeanFactory().setBeanClassLoader(Registry.class.getClassLoader());
    context.setParent(Registry.getGlobalApplicationContext());
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.setDocumentReaderClass(ScopeTenantIgnoreDocReader.class);
    xmlReader.setBeanClassLoader(Registry.class.getClassLoader());
    xmlReader.loadBeanDefinitions(getSpringConfigurationLocations());
    context.refresh();//from  ww w.j av  a2s  .c o m
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
    this.applicationContex = context;
}

From source file:nl.nn.adapterframework.configuration.IbisContext.java

public Object createBeanAutowireByName(Class beanClass) {
    return applicationContext.getAutowireCapableBeanFactory().createBean(beanClass,
            AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
}

From source file:nl.strohalm.cyclos.services.permissions.PermissionServiceImpl.java

@Override
public PermissionCatalogHandler getPermissionCatalogHandler(final Group group) {
    final AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
    try {//from ww  w.j a v  a  2  s. c om
        PermissionCatalogHandlerImpl handler = (PermissionCatalogHandlerImpl) factory.createBean(
                PermissionCatalogHandlerImpl.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
        handler.load(group);
        return handler;
    } catch (Exception e) {
        throw new PermissionCatalogInitializationException(group.getNature(), e.getMessage(), e);
    }
}

From source file:org.apache.struts2.spring.StrutsSpringObjectFactory.java

/**
 * Constructs the spring object factory/*from w w  w. ja  v  a2  s  .c o m*/
 * @param autoWire The type of autowiring to use
 * @param alwaysAutoWire Whether to always respect the autowiring or not
 * @param useClassCacheStr Whether to use the class cache or not
 * @param servletContext The servlet context
 * @since 2.1.3
 */
@Inject
public StrutsSpringObjectFactory(
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE, required = false) String autoWire,
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE_ALWAYS_RESPECT, required = false) String alwaysAutoWire,
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_USE_CLASS_CACHE, required = false) String useClassCacheStr,
        @Inject ServletContext servletContext, @Inject(StrutsConstants.STRUTS_DEVMODE) String devMode,
        @Inject Container container) {

    super();
    boolean useClassCache = "true".equals(useClassCacheStr);
    if (LOG.isInfoEnabled()) {
        LOG.info("Initializing Struts-Spring integration...");
    }

    Object rootWebApplicationContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    if (rootWebApplicationContext instanceof RuntimeException) {
        RuntimeException runtimeException = (RuntimeException) rootWebApplicationContext;
        LOG.fatal(runtimeException.getMessage());
        return;
    }

    ApplicationContext appContext = (ApplicationContext) rootWebApplicationContext;
    if (appContext == null) {
        // uh oh! looks like the lifecycle listener wasn't installed. Let's inform the user
        String message = "********** FATAL ERROR STARTING UP STRUTS-SPRING INTEGRATION **********\n"
                + "Looks like the Spring listener was not configured for your web app! \n"
                + "Nothing will work until WebApplicationContextUtils returns a valid ApplicationContext.\n"
                + "You might need to add the following to web.xml: \n" + "    <listener>\n"
                + "        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n"
                + "    </listener>";
        LOG.fatal(message);
        return;
    }

    String watchList = container.getInstance(String.class, "struts.class.reloading.watchList");
    String acceptClasses = container.getInstance(String.class, "struts.class.reloading.acceptClasses");
    String reloadConfig = container.getInstance(String.class, "struts.class.reloading.reloadConfig");

    if ("true".equals(devMode) && StringUtils.isNotBlank(watchList)
            && appContext instanceof ClassReloadingXMLWebApplicationContext) {
        //prevent class caching
        useClassCache = false;

        ClassReloadingXMLWebApplicationContext reloadingContext = (ClassReloadingXMLWebApplicationContext) appContext;
        reloadingContext.setupReloading(watchList.split(","), acceptClasses, servletContext,
                "true".equals(reloadConfig));
        if (LOG.isInfoEnabled()) {
            LOG.info("Class reloading is enabled. Make sure this is not used on a production environment!",
                    watchList);
        }

        setClassLoader(reloadingContext.getReloadingClassLoader());

        //we need to reload the context, so our isntance of the factory is picked up
        reloadingContext.refresh();
    }

    this.setApplicationContext(appContext);

    int type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; // default
    if ("name".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
    } else if ("type".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
    } else if ("auto".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
    } else if ("constructor".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
    } else if ("no".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_NO;
    }
    this.setAutowireStrategy(type);

    this.setUseClassCache(useClassCache);

    this.setAlwaysRespectAutowireStrategy("true".equalsIgnoreCase(alwaysAutoWire));

    if (LOG.isInfoEnabled()) {
        LOG.info("... initialized Struts-Spring integration successfully");
    }
}

From source file:org.apache.usergrid.tools.ToolBase.java

public void startSpring() {

    // copy("/testApplicationContext.xml", TMP);
    String[] locations = { "toolsApplicationContext.xml" };
    ApplicationContext ac = new ClassPathXmlApplicationContext(locations);

    AutowireCapableBeanFactory acbf = ac.getAutowireCapableBeanFactory();
    acbf.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    acbf.initializeBean(this, "testClient");

    assertNotNull(emf);/*  w  w w  .  jav a  2  s  .  c  o m*/
    assertTrue("EntityManagerFactory is instance of EntityManagerFactoryImpl",
            emf instanceof EntityManagerFactoryImpl);
}

From source file:org.broadleafcommerce.core.web.catalog.taglib.GoogleAnalyticsTag.java

@Override
public void doTag() throws JspException, IOException {
    JspWriter out = getJspContext().getOut();

    if (this.webPropertyId == null) {
        ServletContext sc = ((PageContext) getJspContext()).getServletContext();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    }/* w w w . java 2s . com*/

    String webPropertyId = getWebPropertyId();

    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();
}

From source file:org.codehaus.groovy.grails.plugins.web.api.ControllersApi.java

/**
 * Constructor used by controllers/*  www .j  a  v  a2s.c  o m*/
 *
 * @param instance The instance
 */
public static void initialize(Object instance) {
    ApplicationContext applicationContext = getStaticApplicationContext();
    if (applicationContext == null) {
        return;
    }

    applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(instance,
            AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

    if (Environment.getCurrent() == Environment.TEST) {
        GrailsWebRequest webRequest = GrailsWebRequest.lookup();
        if (webRequest != null) {
            webRequest.setControllerName(GrailsNameUtils.getLogicalPropertyName(instance.getClass().getName(),
                    ControllerArtefactHandler.TYPE));
        }
    }
}

From source file:org.codehaus.groovy.grails.plugins.web.api.ControllersApi.java

/**
 * Initializes a command object.//  w  w  w.ja  v a  2  s. c o m
 *
 * If type is a domain class and the request body or parameters include an id, the id is used to retrieve
 * the command object instance from the database, otherwise the no-arg constructor on type is invoke.  If
 * an attempt is made to retrieve the command object instance from the database and no corresponding
 * record is found, null is returned.
 *
 * The command object is then subjected to data binding and dependency injection before being returned.
 *
 *
 * @param controllerInstance The controller instance
 * @param type The type of the command object
 * @return the initialized command object or null if the command object is a domain class, the body or
 * parameters included an id and no corresponding record was found in the database.
 */
public Object initializeCommandObject(final Object controllerInstance, final Class type) throws Exception {
    final HttpServletRequest request = getRequest(controllerInstance);
    final DataBindingSource dataBindingSource = DataBindingUtils
            .createDataBindingSource(getGrailsApplication(controllerInstance), type, request);
    final DataBindingSource commandObjectBindingSource = WebMetaUtils.getCommandObjectBindingSource(type,
            dataBindingSource);
    final Object commandObjectInstance;
    Object entityIdentifierValue = null;
    if (DomainClassArtefactHandler.isDomainClass(type)) {
        entityIdentifierValue = commandObjectBindingSource.getIdentifierValue();
        if (entityIdentifierValue == null) {
            final GrailsWebRequest webRequest = GrailsWebRequest.lookup(request);
            entityIdentifierValue = webRequest != null ? webRequest.getParams().getIdentifier() : null;
        }
    }
    if (entityIdentifierValue != null) {
        commandObjectInstance = InvokerHelper.invokeStaticMethod(type, "get", entityIdentifierValue);
    } else {
        commandObjectInstance = type.newInstance();
    }

    if (commandObjectInstance != null) {
        final boolean shouldDoDataBinding;

        if (entityIdentifierValue != null) {
            final HttpMethod requestMethod = HttpMethod.valueOf(request.getMethod());
            switch (requestMethod) {
            case PATCH:
            case POST:
            case PUT:
                shouldDoDataBinding = true;
                break;
            default:
                shouldDoDataBinding = false;
            }
        } else {
            shouldDoDataBinding = true;
        }

        if (shouldDoDataBinding) {
            bindData(controllerInstance, commandObjectInstance, commandObjectBindingSource,
                    Collections.EMPTY_MAP, null);
        }

        final ApplicationContext applicationContext = getApplicationContext(controllerInstance);
        final AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext
                .getAutowireCapableBeanFactory();
        autowireCapableBeanFactory.autowireBeanProperties(commandObjectInstance,
                AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    }
    return commandObjectInstance;
}