2012-07-24 4 views
2

Я использую контекст: компонентное сканирование, все же зависимости не вводятся.spring @ inject не работает в контроллере

Вот мои настройки. Свойство ConnectionHelper не вводится в класс LoginController.

WEB-INF/web.xml

<context-param> 
    <param-name>log4jConfigLocation</param-name> 
    <param-value>/WEB-INF/classes/log4j.properties</param-value> 
</context-param> 

<listener> 
    <listener-class> 
     org.springframework.web.context.ContextLoaderListener 
    </listener-class> 
</listener> 

<servlet> 
    <servlet-name>vd</servlet-name> 
    <servlet-class> 
     org.springframework.web.servlet.DispatcherServlet 
    </servlet-class> 
    <load-on-startup>1</load-on-startup> 
</servlet> 



<servlet-mapping> 
    <servlet-name>vd</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 

WEB-INF/applicationContext.xml

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

<context:component-scan base-package="com.example" /> 

</beans> 

WEB-INF/VD-servlet.xml

<?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:mvc="http://www.springframework.org/schema/mvc" 
xmlns:context="http://www.springframework.org/schema/context" 
xsi:schemaLocation="http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 

<!-- Configures Handler Interceptors --> 
<mvc:interceptors> 
    <bean class="com.example.interceptors.SslInterceptor" /> 
    <mvc:interceptor> 
     <mvc:mapping path="/login" /> 
     <bean class="com.example.interceptors.SslInterceptor" /> 
    </mvc:interceptor> 
</mvc:interceptors> 

<mvc:resources mapping="/resources/**" location="/resources/" /> 
<mvc:resources mapping="/WEB-INF/views/**" location="/WEB-INF/views/" /> 

<bean 
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix" value="/WEB-INF/views/" /> 
    <property name="suffix" value=".html" /> 
</bean> 
</beans> 

ком. example.controllers.LoginController.java

@Controller 
public class LoginController { 

@Inject 
private ConnectionHelper connectionHelper; //this is null after loading 

} 

com.example.connection.ConnectionHelper.java

@Component 
public class ConnectionHelper { 

} 

Пожалуйста, скажите мне, что здесь не так ... после нескольких часов поиска неисправностей я не могу определить проблему.

Update

я изменил свою конфигурацию и переехал все на VD-servlet.xml.

Совершенно чудесным образом я обнаружил, что @Autowired работает (с зависимостями вложений) с этой конфигурацией, но @Inject нет.

И <mvc:annotation-driven /> по-прежнему требуется, даже если вы используете <context:component-scan />, в противном случае @RequestMapping не обнаружен.

VD-servlet.xml

<?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:mvc="http://www.springframework.org/schema/mvc" 
xmlns:context="http://www.springframework.org/schema/context" 
xsi:schemaLocation="http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 

<mvc:annotation-driven /> 
<context:component-scan base-package="com.example" /> 

<mvc:interceptors> 
    <bean class="com.example.interceptors.SslInterceptor" /> 
    <mvc:interceptor> 
     <mvc:mapping path="/login" /> 
     <bean class="com.example.interceptors.SslInterceptor" /> 
    </mvc:interceptor> 
</mvc:interceptors> 

<mvc:resources mapping="/resources/**" location="/resources/" /> 
<mvc:resources mapping="/WEB-INF/views/**" location="/WEB-INF/views/" /> 
<bean 
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix" value="/WEB-INF/views/" /> 
    <property name="suffix" value=".html" /> 
</bean> 
</beans> 
+0

Это большой вопрос, с все правильные детали включены.+1 –

ответ

1

Согласен с @Alex, так что файл, где вам не хватает <context:component-scan/> или <context:annotation-config/> не applicationContext.xml файл, но vd-servlet.xml файл.

Либо <context:annnotation-config/> или <context:component-scan/> зарегистрирует AutowiredAnnotationBeanPostProcessor отвечает за обработку @Autowired, @Resource, @Inject аннотаций

+0

Да, согласился поблагодарить за это. +1 –

+0

Я обновил вопрос ... пожалуйста, взгляните на него. –

+0

Как @Alex говорит Сумит, вам нужен mvc: управляемый аннотациями. Компонентное сканирование просто находит все компоненты в пакете, но управляется аннотациями, итерациями по бобам, обнаруживает аннотацию @RequestMapping и создает сопоставление. @Inject должен работать так же, как @Autowired - вы упомянули, что @Autowired работает для вас. Можете ли вы подтвердить, что у вас есть jar, содержащий 'javax.inject.Inject' в вашем пути к классам –

0

Я считаю, что ваш applicationContext.xml отсутствует:

<context:annotation-config>

это регистрирует источники постпроцессоры для конфигурации на основе аннотаций.

+0

'component-scan' делает то же самое, однако в' vd-servlet.xml' отсутствует 'annotation-config/component-scan', добавив, что это должно устранить проблему. –

+0

Но по иронии судьбы, если я пропускаю и просто использую компонент: scan, то @RequestMapping не обнаружены. –

+0

Вам нужно '' –

0

Вам необходимо добавить геттеры и сеттеры в LoginController. Другой вариант - сделать connectionHelper переменной protected. Вот как весна «видит» свойство, которое нужно ввести.

В LoginController:

@Inject 
private ConnectionHelper connectionHelper; 

public ConnectionHelper getConnectionHelper() { 
    return connectionHelper; 
} 

public void setConnectionHelper(ConnectionHelper connectionHelper) { 
    this.connectionHelper = connectionHelper; 
} 
+2

Весна будет вводить частные переменные просто отлично без геттера и сеттера. – digitaljoel

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