Duvida contexto jobScheduler

7 respostas
boneazul

Pessoal tenho um componente de jobScheduler
e anotei ele como

@ApplicationScoped

só que tento injetar um Dao no construtor e ele da NullpointerException na hora de executar , acho que nesse contexto a ID nã acontece

Tem algum contexto que ele faz a injeção de dependencia??
O componente vai rodar de 10 em 10 minutos fazendo algumas validações…

7 Respostas

Lucas_Cavalcanti

vc anotou com @Component (do VRaptor) também?

aonde dá o nullpointer?

boneazul

Lucas Cavalcanti:
vc anotou com @Component (do VRaptor) também?

aonde dá o nullpointer?

Lucas ta anotado com @Component sim pra fazer a injeção!!
Bom uma coisa foi erro meu , esqueci de passar no construtor por isso a NPE,mas mesmo assim o spring ta reclamando de outra coisa agora

SEVERE: Exception starting filter vraptor
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emailSendTask' defined in file [D:\www\contrato\WebContent\WEB-INF\classes\br\com\webtia\contrato\scheduler\EmailSendTask.class]: Unsatisfied dependency expressed through constructor argument with index 1 of type [br.com.webtia.contrato.daos.EmailPanelDao]: : Error creating bean with name 'emailPanelDao': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emailPanelDao': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:698)
	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:984)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:886)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:479)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)
	at br.com.caelum.vraptor.ioc.spring.SpringBasedContainer.start(SpringBasedContainer.java:68)
	at br.com.caelum.vraptor.ioc.spring.SpringProvider.start(SpringProvider.java:79)
	at br.com.caelum.vraptor.VRaptor.init(VRaptor.java:110)
	at br.com.caelum.vraptor.VRaptor.init(VRaptor.java:103)
	at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:275)
	at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:397)
	at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:108)
	at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3800)
	at org.apache.catalina.core.StandardContext.start(StandardContext.java:4450)
	at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
	at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
	at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:526)
	at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:630)
	at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:556)
	at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:491)
	at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1206)
	at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:314)
	at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
	at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
	at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
	at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
	at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
	at org.apache.catalina.core.StandardService.start(StandardService.java:516)
	at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
	at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
	at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emailPanelDao': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:338)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:820)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:762)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:680)
	at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:771)
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:691)
	... 43 more
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
	at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:123)
	at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:40)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
	... 49 more
//Meu componente

@Component
@ApplicationScoped
public class EmailSendTask implements ApplicationTask {
	
        //Esta anotado com @Component
	private EmailPanelDao daoEmailPanel;
	public EmailSendTask(TaskScheduler scheduler,EmailPanelDao daoEmailPanel) {
    	this.daoEmailPanel=daoEmailPanel;
		this.schedule(scheduler);
    }
    public void schedule(TaskScheduler scheduler) {
        scheduler.schedule(this, new CronTrigger("*/59 * * * * *"));
    }
	@Override
	public void run() {
			List<EmailPanel> emails  = daoEmailPanel.listAllNotSended();
			for(EmailPanel email : emails){
				try {
					SendMail.sendMail(email.getTo(),email.getFrom(), email.getSubject(), email.getMessage());
					email.setSended('S');
					email.setSendeddate(Calendar.getInstance().getTime());
					email.setProblem("");
				} catch(Exception e) {
					StringWriter w = new StringWriter();
					email.setSended('N');
					e.printStackTrace(new PrintWriter(w));
					email.setProblem(w.toString());
				}
				daoEmailPanel.update(email);
			}
			
	}
}

Classes que peguei do livro de receitas para fazer a schedluer…

@Component
@ApplicationScoped
public class TaskSchedulerFactory implements ComponentFactory<TaskScheduler> {

    private ThreadPoolTaskScheduler scheduler;
    
    @PostConstruct
    public void create() {
        scheduler = new ThreadPoolTaskScheduler();
        scheduler.initialize();
    }
    
    public TaskScheduler getInstance() {
        return scheduler;
    }
    
    @PreDestroy
    public void destroy() {
        scheduler.destroy();
    }
    
}
@Component
public class EmailPanelDao {

		 private Session session;

		 public EmailPanelDao(Session session){
			 this.session=session;
		 }
.
.
.
Lucas_Cavalcanti

vc tá com os listeners configurados no web.xml? tente tirá-los…

boneazul
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
	<display-name>appName</display-name>
	
	<context-param>  
        <param-name>br.com.caelum.vraptor.encoding</param-name>  
        <param-value>ISO-8859-1</param-value>  
    </context-param>
    
    <context-param>
    <param-name>br.com.caelum.vraptor.provider</param-name>
    <param-value>br.com.caelum.vraptor.util.hibernate.HibernateCustomProvider</param-value>
	</context-param>
	
	<filter>
		<filter-name>vraptor</filter-name>
		<filter-class>br.com.caelum.vraptor.VRaptor</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>vraptor</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>REQUEST</dispatcher>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Não entendi sua resposta de listener todo caso meu web.xml é esse …da uma olhada…

Lucas_Cavalcanti

o problema é que vc tá usando coisas Request scoped (o Dao) dentro de algo que é ApplicationScoped (o Scheduler)

vc não pode fazer isso… pelo menos ainda não é suportado pelo vraptor…

vc vai precisar que esse dao específico seja ApplicationScoped, receba uma SessionFactory no construtor, e abra (e feche) sessões quando for conveniente…

boneazul

Lucas Cavalcanti:
o problema é que vc tá usando coisas Request scoped (o Dao) dentro de algo que é ApplicationScoped (o Scheduler)

vc não pode fazer isso… pelo menos ainda não é suportado pelo vraptor…

vc vai precisar que esse dao específico seja ApplicationScoped, receba uma SessionFactory no construtor, e abra (e feche) sessões quando for conveniente…

Entendi…beleza vo deixar o componente sem Injeção e instanciar na mão mesmo passando session e dando close ja que esse componente é pouco utilizado nesse escopo e muito mais no escopo de request…

Obrigado pela ajuda…

Lavieri

A minha solução pra esse problema q vc tem, e que já tive...

@Component
@ApplicationScoped
public class NoScopedSessionCreator {

	private static final Logger LOGGER = LoggerFactory.getLogger(NoScopedSessionCreator .class);
	private static void debug(String regex, Object ... objects) {
		if (LOGGER.isDebugEnabled())
			LOGGER.debug(String.format(regex, objects));
	}
	
	private final SessionFactory factory;
	
	public NoScopedSessionCreator(final SessionFactory factory) {
		this.factory = factory;
	}
	
	/**
	 * Abre um {@link Session} que não depende do scopo, portanto não será fechado
	 * automaticamente, sendo o <B><U>SEU FECHAMENTO RESPONSABILIDADE DE QUEM ABRIU</U></B>. 
	 * @return {@link Session} com a implementação corrente do aplicativo.
	 */
	public Session crateSession() {
		debug("Session created with out scope");
		return factory.openSession();
	}
}

neste caso é sua responsabilidade cuidar desta sessão e fechala corretamente, para que ela não fique a deriva aberta comendo recurso...

Obs.... se for usar, chame o NoScopedSessionCreator no construtor do seu componente...
Use a sessão dentro do proprio construtor...
feche a sessão ainda dentro do contrutor... assim vc garante que não vai deichar o recurso aberto atoa...

Criado 11 de março de 2010
Ultima resposta 15 de mar. de 2010
Respostas 7
Participantes 3