[英]Injecting dependencies to ServletContextListener
I'm developing a web application and I'm new to Spring Hibernate. 我正在开发一个Web应用程序,并且是Spring Hibernate的新手。 In there I have a ServletContextListener to run a method periodically.
在这里,我有一个ServletContextListener来定期运行一个方法。 In that class I'm calling a method in my ReceiptDao class.
在该类中,我正在我的ReceiptDao类中调用一个方法。
Below is ServletContextListener class 下面是ServletContextListener类
public class MailReminder implements ServletContextListener {
public void contextInitialized(ServletContextEvent arg0) {
ServletContext servletContext = arg0.getServletContext();
System.out.println("ServletContextListener started");
int delay = 1000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
ReceiptDao receiptDao=new ReceiptDao();
receiptDao.listReceipts();
}
},delay, 1000*60);
}
public void contextDestroyed(ServletContextEvent arg0) {
ServletContext servletContext = arg0.getServletContext();
Timer timer = (Timer)servletContext.getAttribute ("timer");
if (timer != null)
timer.cancel();
servletContext.removeAttribute ("timer");
System.out.println("ServletContextListener destroyed");
}
}
Below is the method in ReceiptDao 下面是ReceiptDao中的方法
@Autowired
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public List<Receipt> listReceipts() {
Session session = sessionFactory.openSession(); //line 150
Criteria crit= session.createCriteria(Receipt.class);
crit.add(Restrictions.eq("ReceiptId",2 ));
List<Receipt> receiptlist= crit.list();
session.close();
return receiptlist;
}
It gives a NullPointerException in line 150. I know it happens because I'm calling this method through Spring nonmanaged class. 它在第150行中给出了NullPointerException。我知道发生这种情况是因为我是通过Spring非托管类调用此方法的。 But I have no idea about how to inject my Spring managed ReceiptDao into my ServletContextListener.
但是我不知道如何将Spring管理的ReceiptDao注入到ServletContextListener中。
Could you please tell me how to inject it. 你能告诉我怎么注射吗? Please mention the changes I have to do in my web.xml and spring-config-file.xml too.
请在我的web.xml和spring-config-file.xml中提到我必须做的更改。
To create a new class and to inject other class, you need to create beans. 要创建一个新类并注入其他类,您需要创建bean。
In you case to inject your receiptDAO; 如果您要注入收据DAO; you need to to as following:
您需要如下:
<beans>
<bean id="receiptDAO" class="{path}.ReceiptDao" singleton="true"/>
<bean id="mailReminder" class="{path}.MailReminder" scope="singleton">
<property name="receiptDAO">
<ref bean="receiptDAO"/>
</property>
</bean>
</beans>
In your class just create: 在您的课程中,只需创建:
private ReceiptDao receiptDAO;
public getReceiptDAO()
{
return receiptDAO;
}
And you can use it freely 您可以自由使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.