Java @自动布线没有被注入

Java @自动布线没有被注入,java,spring,autowired,Java,Spring,Autowired,我有两个服务类和一个存储库类。当我尝试将一个服务bean自动连接到另一个服务bean时,一个bean被注入。但是,当我尝试调用该方法时,它会显示一个NullPointerException。请帮帮我。在过去的三天里,我一直在做这个 我的第一个服务舱: @Service public class MetaData implements MetaDataService { private AffiliateRepository util; @Autowired publ

我有两个服务类和一个存储库类。当我尝试将一个服务bean自动连接到另一个服务bean时,一个bean被注入。但是,当我尝试调用该方法时,它会显示一个
NullPointerException
。请帮帮我。在过去的三天里,我一直在做这个

我的第一个服务舱:

@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 {
                                }
    }
}
我的第二个服务级别:

@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 {
                                }
    }
}
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd“version=“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>
resetpwd Web应用程序
重置pwd
hiddenHttpMethodFilter
org.springframework.web.filter.hiddenhttmpmethodfilter
hiddenHttpMethodFilter
重置pwd
/*
重置pwd
org.springframework.web.servlet.DispatcherServlet
上下文配置位置
classpath*:spring/servlet-context.xml
1.
重置pwd
/
编码滤波器
org.springframework.web.filter.CharacterEncodingFilter
编码
UTF-8
强制编码
真的
编码滤波器
/*
持久性/重置PWD单元
重置PWD单元
持久性/重置pwd上下文
重置PWD单元
welcome.jsp
欢迎光临
index.html
index.jsp
下面是servlet-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;
        }

/403
公共映射validate()引发IOException{
高级验证(错误);
}
公共无效高级验证(映射错误){
如果(!id.contains(“@”)和&md.findByRacf(){
//基于racf找到唯一的附属机构(可能是主要的或
//二级)
}else if(id.contains(“@”)和&md.findByEmail(){
//基于电子邮件找到了唯一的附属公司
}否则{
//找不到唯一的附属机构记录
错误.put(“id”,“resetpw.nouiserinfo”);
返回;
}

我脑海中只有一种可能的解释:加载了不止一个上下文,并且实际上有两个NPE发生的类的不同bean实例——一个有注入依赖项,另一个没有注入依赖项(导致NPE)


由于您使用的是Spring mvc,您可以查看一下,并获取有关可能原因的更多信息。

试试这个。只要您保持一致,这个范例就可以工作:

@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;
}

您应该检查您的
persistence.xml
,以确保它与持久性单元正确配合。

您在
ResetPasswordForm
类中声明了两个构造函数。Spring容器可能为同一类创建了一个重复实例,一个
带有参数,另一个
带有默认constructor
。尝试删除默认的构造函数创建。它应该可以工作。

发布真实代码,发布完整的异常堆栈跟踪。使用字段注入或构造函数注入。无需两者都做。您在哪里调用advancedValidation?您好,我已经添加了web.xml和servlet-context.xml文件,您可以研究一下吗e我想我没有创建多个上下文。@Myrna你能发布调用
advancedValidation
的代码吗?我在上面的问题中添加了advancedValidation。你能研究一下主要问题吗?我的意思是,你能展示调用
advancedValidation
方法的代码吗?更准确地说,你是怎么做的您获取调用此方法的
ResetPasswordForm
实例?private MetaDataService md;@Autowired public ResetPasswordForm(MetaDataService md){this.md=md;//在iam调试时,我可以看到此时注入了bean。}
@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
   }
}