2015-06-22 3 views
1

У меня есть два класса обслуживания и один класс репозитория. Когда я пытаюсь автоуведовать один сервисный компонент в другой сервисный компонент, один компонент получает инъекцию. Но когда я пытаюсь вызвать метод, он показывает NullPointerException. Пожалуйста, помогите мне. Я застрял в этом последние 3 дня.@autowiring не вводится

мой первый класс обслуживания:

@Service 
public class MetaData implements MetaDataService { 


    private AffiliateRepository util; 

    @Autowired 
    public MetaData(AffiliateRepository util) { 
     this.util = util;// I can see bean getting injected 
    } 

    public boolean findByEmail() { 

     // some logic 
    } 

} 

мой второй класс обслуживания:

@Service 
public class ResetPasswordForm implements ResetPasswordFormService { 

    public ResetPasswordForm() { 

    } 

      private MetaDataService md; 

    @Autowired 
    public ResetPasswordForm(MetaDataService md) { 
     this.md = md; // when iam debugging I could see bean got injected at this point. 
    } 

    public void advancedValidation(Map<String, String> errors) { 

     else if (id.contains("@") && md.findByEmail())// when iam calling method present in class using md it is showing md is null { 
           } 
    } 
} 

мой репозиторий класс:

@Repository 
public class JpaAffiliate implements AffiliateRepository, Serializable { 
    private EntityManagerFactory emf; 

    @PersistenceUnit(unitName="resetpwd-unit") 
    public void setEntityManagerFactory(EntityManagerFactory emf) { 
     this.emf = emf; 
    } 

    @SuppressWarnings("unchecked") 
    public List<Affiliate> findAffiliate(String value) { 
     // calls to database 
    } 
} 

Я пробовал все (например. <context:component-scan base-package>, который указывает на мой базовый пакет). В чем может быть проблема?

ниже мой полный StackTrace

ResetPasswordForm.java:134) [classes:] 
    at (ResetPasswordForm.java:119) [classes:] 
    at ...resetpwd.web.Page.getPage(Page.java:38) [classes:] 
    at ....web.ResetPasswordController.addContact(ResetPasswordController.java:52) [classes:] 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_55] 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_55] 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_55] 
    at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_55] 
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) [jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar:1.0.2.Final-redhat-1] 
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) [spring-webmvc-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar:1.0.2.Final-redhat-1] 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE] 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] 
    at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] 
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) [jboss-as-web-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] 
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:488) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.coyote.ajp.AjpProtocol$AjpConnectionHandler.process(AjpProtocol.java:420) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1] 
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_55] 

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd»версия = "3,0">

мой web.xml файл

<description>resetpwd Web Application</description> 
    <display-name>resetpwd</display-name> 


    <filter> 
    <filter-name>hiddenHttpMethodFilter</filter-name> 
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 
    </filter> 

    <filter-mapping> 
    <filter-name>hiddenHttpMethodFilter</filter-name> 
    <servlet-name>resetpwd</servlet-name> 
    <url-pattern>/*</url-pattern> 
    </filter-mapping> 


    <servlet> 
     <servlet-name>resetpwd</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>classpath*:spring/servlet-context.xml</param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>resetpwd</servlet-name> 
     <url-pattern>/</url-pattern> 
    </servlet-mapping> 
    <filter> 
     <filter-name>encodingFilter</filter-name> 
     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 
     <init-param> 
      <param-name>encoding</param-name> 
      <param-value>UTF-8</param-value> 
     </init-param> 
     <init-param> 
      <param-name>forceEncoding</param-name> 
      <param-value>true</param-value> 
     </init-param> 
    </filter> 

    <filter-mapping> 
     <filter-name>encodingFilter</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 

    <!-- uncomment JPA support persistence unit configuration below --> 

    <persistence-unit-ref> 
     <persistence-unit-ref-name>persistence/resetpwd-unit</persistence-unit-ref-name> 
     <persistence-unit-name>resetpwd-unit</persistence-unit-name> 
    </persistence-unit-ref> 

    <persistence-context-ref> 
    <persistence-context-ref-name>persistence/resetpwd-context</persistence-context-ref-name> 
    <persistence-unit-name>resetpwd-unit</persistence-unit-name> 
    </persistence-context-ref> 


    <!-- uncomment JPA support persistence unit configuration above --> 

    <welcome-file-list> 
     <welcome-file>welcome.jsp</welcome-file> 
     <welcome-file>welcome.html</welcome-file> 
     <welcome-file>index.html</welcome-file> 
     <welcome-file>index.jsp</welcome-file> 
    </welcome-file-list> 

</web-app> 

здесь сервлет-context.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!-- 
    DispatcherServlet context for applications web tier 
--> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:p="http://www.springframework.org/schema/p" 
     xmlns:security="http://www.springframework.org/schema/security" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xmlns:jee="http://www.springframework.org/schema/jee" 
     xsi:schemaLocation="http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc.xsd 
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans.xsd 
      http://www.springframework.org/schema/security 
      http://www.springframework.org/schema/security/spring-security.xsd 
      http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/jee 
     http://www.springframework.org/schema/jee/spring-jee.xsd      
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context.xsd"> 

    <security:debug/> 

    <import resource="servlet-view.xml"/> 



    <context:component-scan base-package="edu.ucsd.act.core.resetpwd" /> 



    <!-- turns on support for mapping requests to Spring MVC @Controller methods. also registers default Formatters and validators for use across all @Controllers --> 
    <mvc:annotation-driven conversion-service="conversionService"/> 

    <!-- all resources (css,js,jpg,png,bmp) inside folder (src/main/webapp/resources) are mapped so they can be referred to inside JSP files (see header.jsp for more details) --> 
    <mvc:resources mapping="/resources/**" location="/resources/"/>  



    <bean id="expressionHandler" class="edu.ucsd.act.core.coresecurity.requiresaction.MethodExpressionHandler" /> 


    <!-- static case, no java controller needed --> 
    <mvc:view-controller path="/" view-name="welcome" /> 

    <!-- serve all static resources (*.html,...) from src/main/webapp/ -->  
    <mvc:default-servlet-handler/> 

    <!-- [J] customized --> 
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 

     <!-- [1] remove default formatters --> 
     <property name="registerDefaultFormatters" value="false" /> 

     <!-- [2] establish exact formatters that are desired --> 
     <property name="formatters"> 
      <set> 
       <bean class="org.springframework.format.number.NumberFormatAnnotationFormatterFactory" /> 
       <!-- add additional business formatters here --> 
      </set> 
     </property> 

     <!-- [3] alter formatter to match your business requirement --> 
     <property name="formatterRegistrars"> 
      <set> 
       <bean class="org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar"> 
        <property name="dateFormatter"> 
         <bean class="org.springframework.format.datetime.joda.DateTimeFormatterFactoryBean"> 
          <property name="pattern" value="yyyyMMdd"/> 
         </bean> 
        </property> 
       </bean> 
      </set> 
     </property> 
    </bean> 

    <!-- 
     - Message source for this context, loaded from localized "messages_xx" files. 
     - Files are stored inside src/main/resources 
    --> 
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages/messages" p:fallbackToSystemLocale="false"/> 

    <!-- [J] register "global" interceptor beans to apply to all registered HandlerMappings --> 
    <mvc:interceptors> 
     <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/> 
     <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/> 
    </mvc:interceptors> 

    <!-- [J] store preferred language configuration in a cookie --> 
    <bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver" id="localeResolver" p:cookieName="locale"/> 

    <!-- [J] resolves localized <theme_name>.properties files in the classpath to allow for theme support, store configuration in a cookie 
    <bean class="org.springframework.ui.context.support.ResourceBundleThemeSource" id="themeSource"/> 
    <bean class="org.springframework.web.servlet.theme.CookieThemeResolver" id="themeResolver" p:cookieName="theme" p:defaultThemeName="standard"/> 
    --> 

    <!-- This bean resolves specific types of exceptions to corresponding logical - view names for error views. The default behavior of 
     DispatcherServlet - is to propagate all exceptions to the servlet container: this will happen - here with all other types of exceptions. --> 
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 

     <!-- view name resolved using bean of type InternalResourceViewResolver (declared in servlet-view.xml) --> 
     <property name="defaultErrorView" value="exception"/> 

     <!-- results into 'WEB-INF/views/exception.jsp' --> 
     <property name="warnLogCategory" value="warn"/> 

     <property name="exceptionMappings"> 
      <props> 
       <!-- spring security --> 
       <prop key="org.springframework.security.access.AccessDeniedException">/403</prop> 
      </props> 
     </property> 
    </bean> 

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver"> 
     <property name="order" value="1"/> 
    </bean> 
    <bean class="org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver" > 
     <property name="order" value="2"/> 
    </bean> 

    <!-- developer may wish to further customize final exception handler --> 
    <bean class="edu.ucsd.act.core.resetpwd.util.AppHandlerExceptionResolver"> 
     <property name="order" value="3"/> 
    </bean> 

    <!-- Enable this for eventual integration of file upload functionality 
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver" /> 
    --> 

    <tx:annotation-driven mode="aspectj" 
     transaction-manager="transactionManager" /> 

    <bean id="app" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> 
<jee:jndi-lookup id="resetpwd-unit" jndi-name="persistence/resetpwd-unit" /> 

</beans> 


public Map<String, String> validate() throws IOException { 

advancedValidation(errors); 

} 


public void advancedValidation(Map<String, String> errors) { 



     if (!id.contains("@") && md.findByRacf()) { 
      // found a unique affiliate based on racf (may be primary or 
      // secondary) 
     } else if (id.contains("@") && md.findByEmail()) { 
      // found a unique affiliate based on email 
     } else { 
      // a unique affiliate record could not be located 
      errors.put("id", "resetpw.nouiserinfo"); 
      return; 
     } 
+3

Опубликовать реальный код, опубликовать полную сводку стека исключений. –

+3

Используйте либо инъекцию поля, либо инъекцию конструктора. Нет необходимости делать то и другое. –

+2

где вы называете advancedValidation? –

ответ

0

Есть только одно возможное объяснение, которое приходит мне на ум: у вас загружено более одного контекста, и у вас на самом деле есть два разных экземпляра компонента, в которых происходит NPE, - один с инъецируемой зависимостью и один без него (вызывающий НПЭ).

Поскольку вы используете Spring mvc, вы можете посмотреть here, here и here для получения дополнительной информации о возможной причине.

+0

Привет, Я добавил файлы web.xml и servlet-context.xml, не могли бы вы заглянуть в это, потому что я не думаю, что создал несколько контекстов. – Myrna

+0

@Myrna Не могли бы вы вывести код, в котором вы вызываете 'advancedValidation'? –

+0

привет спасибо за ответ – Myrna

0

Попробуйте это. Эта парадигма работает так долго, как вы последовательны:

@Service 
public class MetaData implements MetaDataService { 

    public boolean findByEmail() { 
     this.affiliateRepository.someMethod(); 
     // some logic 
    } 

    //I like to autowire at the bottom - keep all the glamour up front 
    @Autowired 
    private AffiliateRepository affiliateRepository; 
} 

Ваши другие услуги:

@Service 
public class ResetPasswordForm implements ResetPasswordFormService { 

    public ResetPasswordForm() {} 

    public void advancedValidation(Map<String, String> errors) { 

     if (someJunk) { 
     } 
     else if (id.contains("@") && metaData.findByEmail()) { 
     } 
     else { 
     } 
    } 

    //your ORM, if you have one, may complain if this is an interface 
    @Autowired 
    private MetaData metaData; 
} 

Я обычно не использовать EntityManager (я использую SessionFactory), но я бы себе представить, что было бы что-то вроде:

@Repository 
@Transactional 
public class AffiliateRepositoryImpl implements AffiliateRepository, Serializable { 

    @PersistenceContext 
    private EntityManager entityManager; 

    @SuppressWarnings("unchecked") 
    @Transactional(readOnly = true, timeout = 10) 
    public List<Affiliate> findAffiliate(String value) { 
    // calls to database 
    } 
} 

Вы должны проверить ваш persistence.xml, чтобы убедиться, что он правильно defined с единицы сохранения.

1

Вы указали два конструктора в своем классе ResetPasswordForm. Вероятно, Spring-контейнер мог создать дубликат экземпляра для одного класса with parameter и другого с default constructor. Попробуйте удалить создание конструктора по умолчанию. Он должен работать.