2014-11-09 3 views
0

Когда я пытаюсь запустить мое приложение вне затмения, я получаю следующее сообщение об ошибке:Spring ошибки инстанцирование Bean

Ошибка создания боба с именем «naLdap»: Инстанцирование боба не удался; Вложенное исключение - org.springframework.beans.BeanInstantiationException: не удалось создать экземпляр класса bean [org.springframework.ldap.core.LdapTemplate]: конструктор сделал исключение; вложенное исключение - java.lang.NullPointerException

Поиск всех сообщений, я только нахожу примеры использования проверки подлинности Spring. В этом случае я ищу три разных экземпляра Ldap на основе региона. Любая помощь/понимание будут с благодарностью оценены.

Конфигурация выглядит следующим образом:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:ldap="http://www.springframework.org/schema/ldap" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/ldap http://www.springframework.org/schema/ldap/spring-ldap.xsd"> 

    <ldap:context-source 
      url="ldap://corporate.root.corp:389" 
      base="dc=corporate, dc=root, dc=corp" 
      username="xyz" 
      password="xyz" 
      referral="follow" 
      id="na-context" /> 

    <ldap:context-source 
      url="ldap://europe.root.corp:389" 
      base="DC=europe,DC=root,DC=corp" 
      username="xyz" 
      password="xyz" 
      referral="follow" 
      id="europe-context" /> 

    <ldap:context-source 
      url="ldap://asia-pac.root.corp:389" 
      base="DC=asia-pac,DC=root,DC=corp" 
      username="xyz" 
      password="xyz" 
      referral="follow" 
      id="asia-context" /> 


    <ldap:ldap-template id="naLdap" context-source-ref="na-context" /> 
    <ldap:ldap-template id="asiaLdap" context-source-ref="asia-context" /> 
    <ldap:ldap-template id="europeLdap" context-source-ref="europe-context" /> 

    <bean id="personRepo" class="com.test.users.repo.PersonRepoImpl"> 
     <property name="naTemplate" ref="naLdap" /> 
     <property name="asiaTemplate" ref="asiaLdap" /> 
     <property name="europeTemplate" ref="europeLdap" /> 
    </bean> 

</beans> 

Реализация:

/** 
* 
*/ 
package com.test.users.repo; 

import static org.springframework.ldap.query.LdapQueryBuilder.query; 

import java.util.ArrayList; 
import java.util.List; 

import org.springframework.ldap.core.LdapTemplate; 
import org.springframework.ldap.filter.AndFilter; 
import org.springframework.ldap.filter.EqualsFilter; 

import com.test.users.beans.Person; 
import com.test.users.ldap.mappers.PersonAttributeMapper; 
import com.test.users.utils.LdapRegionsEnum; 

/** 
* @author 
* 
*/ 
public class PersonRepoImpl implements PersonRepo { 

    private LdapTemplate naTemplate; 
    private LdapTemplate asiaTemplate; 
    private LdapTemplate europeTemplate; 
    private String   networkId; 

    /** 
    * 
    */ 
    public PersonRepoImpl() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 

    /* 
    * (non-Javadoc) 
    * 
    * @see 
    * com.valspar.users.repo.PersonRepo#getAllPersons(com.valspar.users.utils 
    * .LdapRegionsEnum) 
    */ 
    @Override 
    public List<Person> getAllPersons(LdapRegionsEnum region) { 
     PersonAttributeMapper mapper = new PersonAttributeMapper(); 
     AndFilter filter = new AndFilter(); 
     filter.and(new EqualsFilter("objectClass", "person")); 
     LdapTemplate template = null; 
     switch (region) { 
      case ASIA: 
       template = this.getAsiaTemplate(); 
       break; 
      case EUROPE: 
       template = this.getEuropeTemplate(); 
       break; 
      default: 
       template = this.getNaTemplate(); 
     } 
     return template.search(
       query().where("objectclass").is("person").and("samAccountName") 
         .like(networkId), mapper); 
    } 

    @SuppressWarnings("unchecked") 
    public List<Person> getAllPersons() { 

     List<Person> people = new ArrayList<Person>(); 
     for (LdapRegionsEnum region : LdapRegionsEnum.values()) { 
      people.addAll(getAllPersons(region)); 
     } 
     return people; 
    } 

    /** 
    * @return the networkId 
    */ 
    public String getNetworkId() { 
     return networkId; 
    } 

    /** 
    * @param networkId 
    *   the networkId to set 
    */ 
    public void setNetworkId(String networkId) { 
     this.networkId = networkId; 
    } 

    /** 
    * @return the naTemplate 
    */ 
    public LdapTemplate getNaTemplate() { 
     return naTemplate; 
    } 

    /** 
    * @param naTemplate 
    *   the naTemplate to set 
    */ 
    public void setNaTemplate(LdapTemplate naTemplate) { 
     this.naTemplate = naTemplate; 
    } 

    /** 
    * @return the asiaTemplate 
    */ 
    public LdapTemplate getAsiaTemplate() { 
     return asiaTemplate; 
    } 

    /** 
    * @param asiaTemplate 
    *   the asiaTemplate to set 
    */ 
    public void setAsiaTemplate(LdapTemplate asiaTemplate) { 
     this.asiaTemplate = asiaTemplate; 
    } 

    /** 
    * @return the europeTemplate 
    */ 
    public LdapTemplate getEuropeTemplate() { 
     return europeTemplate; 
    } 

    /** 
    * @param europeTemplate 
    *   the europeTemplate to set 
    */ 
    public void setEuropeTemplate(LdapTemplate europeTemplate) { 
     this.europeTemplate = europeTemplate; 
    } 

} 

Вот как я инстанцировании:

ApplicationContext context = new ClassPathXmlApplicationContext(
     "ldap-config.xml"); 

PersonRepo simpleSearch = context.getBean("personRepo", 
     PersonRepo.class); 

Полный трассировки стека:

Error creating bean with name 'naLdap': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.ldap.core.LdapTemplate]: Constructor threw exception; nested exception is java.lang.NullPointerException 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'naLdap': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.ldap.core.LdapTemplate]: Constructor threw exception; nested exception is java.lang.NullPointerException 
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076) 
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021) 
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) 
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) 
     at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) 
     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) 
     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) 
     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) 
     at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700) 
     at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) 
     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) 
     at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) 
     at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) 
     at com.test.users.LoadUsersFromAD.getAllUsersToExamine(LoadUsersFromAD.java:330) 
     at com.test.users.LoadUsersFromAD.run(LoadUsersFromAD.java:102) 
     at java.lang.Thread.run(Unknown Source) 
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.ldap.core.LdapTemplate]: Constructor threw exception; nested exception is java.lang.NullPointerException 
     at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164) 
     at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) 
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069) 
     ... 15 more 
Caused by: java.lang.NullPointerException 
     at org.springframework.ldap.odm.core.impl.DefaultObjectDirectoryMapper.isAtLeast30(DefaultObjectDirectoryMapper.java:80) 
     at org.springframework.ldap.odm.core.impl.DefaultObjectDirectoryMapper.<init>(DefaultObjectDirectoryMapper.java:71) 
     at org.springframework.ldap.core.LdapTemplate.<init>(LdapTemplate.java:93) 
     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
     at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
     at java.lang.reflect.Constructor.newInstance(Unknown Source) 
     at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148) 
     ... 17 more 
+3

Просьба отправить полный стек из NullPointerException. – dunni

+0

Извините, я добавил полный след к исходному сообщению. – pcroadkill

ответ

2

EDIT: Это ошибка в Spring LDAP 2.0.0. Убедитесь, что вы используете, по крайней мере 2.0.1 или 2.0.2 (последняя версия)

Вот мой первый ответ, как объяснение:

Очевидно согласно вашему StackTrace Spring есть проблемы, чтобы определить версию Spring. Позвольте мне объяснить, что происходит:

Spring LDAP пытается определить, если используемая версия Spring больше 3.0 (происходит в методе isAtLeast30). Это делается с использованием информации из MANIFEST.MF из весенней банки (в частности, ключевой версии реализации). Если эта информация отсутствует (например, поскольку у вас есть переупакованная версия Spring), версия реализации возвращает null, что вызывает это исключение NullPointerException.

Таким образом, вы должны проверить, имеет ли ваш ядро ​​с сердечником пружины правильный MANIFEST.MF (в папке META-INF). Возможно также, что у вас есть правильный MANIFEST.MF, но метаданные не могут быть получены загрузчиком классов. В этом случае вы не можете ничего сделать, кроме подачи ошибки в проекте Spring LDAP, потому что они не обрабатывают этот случай в методе.

+0

Благодарим вас за помощь. Ваше решение исправило это. – pcroadkill

+0

В моем случае я работал над старым проектом, и это исключение NPE появилось. Не знаю, как это получилось, но мой Spring Spring LDAP Core 2.0.0.RELEASE собирал неправильный файл манифеста в определенных сценариях. Я указал версию реализации в манифесте моей войны на 2.0.0.RELEASE, и NPE ушел. Это будет полезной остановкой при работе над обновлением зависимостей. Благодаря! – Michael

Смежные вопросы