Подтвердить что ты не робот

Как @Autowire объекты в классах Validator?

Можно ли Autowire объект в классе Validation? Я продолжаю получать null для объекта, который должен быть Autowired...

4b9b3361

Ответ 1

Является ли ваш класс проверки включенным Spring bean? Если нет, вы всегда получите null для своего объекта автоматически. Убедитесь, что вы включили свой класс проверки.

И не забудьте включить постпроцессор Annotation config bean (см. элемент < context: annotation-config/ > )

<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:annotation-config />
</beans>

Как включить класс Validation в качестве управляемого Spring bean. Либо

1 ° Используя xml (как показано выше)

<beans ...>
    <bean class="AccessRequestValidator"/>
    <context:annotation-config />
</beans>

2 ° Вместо использования аннотации (Примечание @Компонент чуть выше класса)

@Component
public class AccessRequestValidator implements Validator {

}

Но, чтобы включить сканирование аннотированных компонентов Spring, вы должны включить bean -post-процессор (уведомление < контекст: компонент-сканирование)

<beans ...>
    <context:annotation-config />
    <context:component-scan base-package="<PUT_RIGHT_HERE_WHICH_ROOT_PACKAGE_SHOULD_SPRING_LOOK_FOR_ANY_ANNOTATED_BEAN>"/>
</beans>

Внутри вашего контроллера просто сделайте это ( Не используйте новый оператор)

Выберите одну из следующих стратегий

public class MyController implements Controller {

    /**
      * You can use FIELD @Autowired
      */
    @Autowired
    private AccessRequestValidator accessRequestValidator;

    /**
      * You can use PROPERTY @Autowired
      */
    private AccessRequestValidator accessRequestValidator;
    private @Autowired void setAccessRequestValidator(AccessRequestValidator accessRequestValidator) {
        this.accessRequestValidator = accessRequestValidator;
    }

    /**
      * You can use CONSTRUCTOR @Autowired
      */
    private AccessRequestValidator accessRequestValidator;

    @Autowired
    public MyController(AccessRequestValidator accessRequestValidator) {
        this.accessRequestValidator = accessRequestValidator;
    }   

}

UPDATE

Структура вашего веб-приложения должна выглядеть как

<CONTEXT-NAME>/
       WEB-INF/
           web.xml
           <SPRING-SERVLET-NAME>-servlet.xml
           business-context.xml
           classes/
               /com
                   /wuntee
                       /taac
                           /validator
                               AccessRequestValidator.class
           lib/
               /**
                 * libraries needed by your project goes here
                 */

Ваш web.xml должен выглядеть (NOTICE contextConfigLocation context-param и ContextLoaderListener)

<web-app version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                       http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--If your business-context.xml lives in the root of classpath-->
        <!--replace by classpath:business-context.xml-->
        <param-value>
            /WEB-INF/business-context.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name><SPRING-SERVLET-NAME></servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name><SPRING-SERVLET-NAME></servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
</web-app>

Ваш < SPRING -SERVLET-NAME > -servlet.xml должен выглядеть (обратите внимание, что я использую Spring 2.5 - заменить, если вы используете 3.0)

 <beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <!--ANY HANDLER MAPPING-->
    <!--ANY VIEW RESOLVER-->
    <context:component-scan base-package="com.wuntee.taac"/>
    <context:annotation-config/>
</beans>

Ответ 2

Попытка следовать тому, что вы показываете выше, я все равно получаю нулевой указатель:

context.xml:

<context:annotation-config />
<context:component-scan base-package="com.wuntee.taac"/>

AccessRequestValidator.java

package com.wuntee.taac.validator;

@Component
public class AccessRequestValidator implements Validator {

    @Autowired
    private UserAccessCache userAccessCache;
...
}

бизнес-context.xml:

   <bean id="userAccessCache" class="com.wuntee.taac.controller.UserAccessCache">
        <property name="cadaDao" ref="cadaDao" />
        <property name="adDao" ref="adDao" />
   </bean>

Сканер рекурсивно сканирует дерево?