[RESOLVIDO]@Autowired não funciona

Olá amigos, estou com uma aplicação que utiliza o spring.

Tenho o meu applicationContext.xml localizado no WEB-INF e está todo configurado.

<context:component-scan base-package="br.com.teste" annotation-config="true" />

E no web.xml possuo as linhas:

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

Minhas classes estão anotadas. Exem: ClienteDAOImpl com o @Repository -> ClienteBOImpl com o @Component -> ClienteService com o @Service -> ClienteAction com o @Component;

Estou dando um:

@Autowired private ClienteService clienteService;

Mas ele vem nulo.

Caso eu não utilize o @Autorired e fizer assim:

appContext = new ClassPathXmlApplicationContext( "applicationContext.xml"); clienteService = (ClienteService) appContext.getBean("ClienteService");

Ele funciona.

Tenta assim pra ver…

    @Autowired  
    @Qualifier("ClienteService")
    private ClienteService clienteService;  

Ainda foi nulo.

joga isso no seu applicationContext.xml

<context:component-scan base-package=“br.com.teste” />

Na primeira postagem mostrei todos os meus arquivos utilizados, o qual tambem mostra que ja setei isso no meu applicationContext.xml

perdão, n tinha visto!
coloca o seu .xml

tem problema?

vc add essta tag tb?

context:annotation-config

Na hora de subir a aplicação não da nenhuma exception?
Só acontece com essa classe?

Na minha config esta sem o “annotation-config”, e as annotations funcionam normalmente…

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

[code]<?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: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”>

<!-- Aqui fica o pessoal que cuida do hibernate -->

     &lt;!-- Auto scan the components --&gt;
     &lt;context:component-scan base-package="br.com.struts"/&gt;
     	
     	&lt;context:annotation-config /&gt;

</beans>[/code]

Ola amigo, fiz o seguinte, mudei o @Component do meu Action para @Controller e deu isso:

[code]SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘clienteAction’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.struts.controller.cliente.negocio.ClienteService br.com.struts.view.cliente.ClienteAction.clienteService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [br.com.struts.controller.cliente.negocio.ClienteService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=ClienteService)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.struts.controller.cliente.negocio.ClienteService br.com.struts.view.cliente.ClienteAction.clienteService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [br.com.struts.controller.cliente.negocio.ClienteService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=ClienteService)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
… 23 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [br.com.struts.controller.cliente.negocio.ClienteService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=ClienteService)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
… 25 more

Fev 17, 2013 10:53:07 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘clienteAction’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.struts.controller.cliente.negocio.ClienteService br.com.struts.view.cliente.ClienteAction.clienteService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [br.com.struts.controller.cliente.negocio.ClienteService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=ClienteService)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.struts.controller.cliente.negocio.ClienteService br.com.struts.view.cliente.ClienteAction.clienteService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [br.com.struts.controller.cliente.negocio.ClienteService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=ClienteService)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
… 23 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [br.com.struts.controller.cliente.negocio.ClienteService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=ClienteService)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
… 25 more
[/code]

annota seu service com @Qualifier(“clienteService”)

Percebi que em cima ele faz uma pre instanciação do singleton:

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5d5a271e: defining beans [dataSource,sessionFactory,clienteDAOImpl,clienteBOImpl,clienteService,clienteAction,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy

Daí repare que o ClienteService, para ele é clienteService.

Daí troquei o @Qualifier(“ClienteService”) para @Qualifier(“clienteService”) e ele não deu o erro no console, mas ainda vem nulo.

Anotei meu service com @Qualifier, mas ainda não funciona,

ele deixou de dar o erro no stackTrace mas ainda vem nulo;

@Service @Qualifier("clienteService") public class ClienteService {

Você tá tentando integrar o spring com o struts? Já leu como fazer isto na documentação?

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/web-integration.html#struts

Pelo que eu percebi, na sua primeira tentativa (sem usar a anotação Controller), o contexto do Spring não subiu, por isto que só funciona manualmente. Mas a anotação Controller é pro SpringMVC… pro struts deve ser diferente, como tá na doc.

Sim amigo, muito obrigado.

Não só vi que para o struts precisa de configuração especifica, mas também pro danado do JSF ( que eu gosto mais hehe ), é add um Jar especifico na configuração e dizer que agora é o spring que controla a injeção.

Encontrei a resposta aqui:

http://struts.apache.org/release/2.2.x/docs/spring-plugin.html