Using injection in non-spring containers

Source: Internet
Author: User

In the case of projects, there are often a lot of situations in the non-spring containers need to use the spring-managed components, such as: Timers, servlets, interceptors, etc., in this case usually want to use the database operation will feel weak, because in this environment, You want to invoke the relevant DAO layer of things, often want to use dependency injection to achieve, but often run out of is a null pointer exception.

As an example:

public class TaskManager implements Servletcontextlistener {//daily milliseconds public static final long day = 86400000;//Timer private Timer timer;//@Autowired//Private gamesettask gamesettask;/** * Stop task at end of web App */public void contextdestroyed (Servletco Ntextevent SCE) {timer.cancel ();//Timer Destroy}/** * Initialize task */public void contextinitialized (Servletcontextevent SCE) at web App startup {Springbeanautowiringsupport.processinjectionbasedoncurrentcontext (this);//define timer Calendar C = calendar.getinstance (); C.add (calendar.date, 1); C.set (C.get (calendar.year), C.get (Calendar.month), C.get (Calendar.day_of_month), 0, 0, 0) ; timer = new timer (true); Gamesettask gamesettask = new Gamesettask ()///Timer.schedule (Locationtask, C.gettime (), day)//timed execution; The timer executes timer.schedule daily 0 o'clock in the morning (Gamesettask, 5000, 4 * 60 * 1000); 5 Seconds after boot execution, after every 1 hours in execution//timer.schedule (Gamesettask, 5000, 5 * 1000);}}

This is a very non-identical timer, which is designed to perform the Gamesettask task regularly when the service is started.

The specific tasks are as follows:

Package Com.smartsoft.task;import Java.util.date;import Java.util.timertask;import net.sf.json.jsonobject;import Org.apache.commons.httpclient.httpclient;import Org.apache.commons.httpclient.methods.postmethod;import Org.apache.commons.httpclient.methods.requestentity;import Org.apache.commons.httpclient.methods.stringrequestentity;import org.apache.commons.lang.math.RandomUtils; Import Org.springframework.beans.factory.annotation.autowired;import org.springframework.stereotype.Component; Import Org.springframework.web.context.support.springbeanautowiringsupport;import com.smartsoft.common.Constants ; import Com.smartsoft.dao.gamesetdao;import Com.smartsoft.service.GamesetService; @Component ("Gamesettask") public  Class Gamesettask extends TimerTask {private static Boolean isrunning = false;private static int t = 1;p rivate static int i = 1; @Autowiredprivate gamesetservice gamesetservice; @Autowiredprivate Gamesetdao gamesetdao;public gamesettask () { Springbeanautowiringsupport.processinjectioNbasedoncurrentcontext (this);} @Overridepublic void Run () {if (!isrunning) {isrunning = true; SYSTEM.OUT.PRINTLN ("-----ganmeset add-------"); Addgemest (); isrunning = false;} else {System.out.println ("-----ganmeset error-------");}} private void Addgemest () {if (t==1) {System.out.println ("---------request:newgameset-------------"); sendhttprequest ("{\" api_key\ ": \" test "+i+" \ ", \" table_no\ ": \" a001\ ", \" computer_name\ ": \" computer001\ ", \" game_set\ ": \" "+i+" \ ", \" Shoe_of_the_day\ ": \" "+i+" \ ", \" game_time\ ": \" "+new Date () +" \ ", \" status\ ": \" 1\ "}", "http://127.0.0.1:8080/bdb/ Gameset!newgameset ", Constants.http_content_type_application_json);} Else{int TTT = Randomutils.nextint (3); String res = ""; if (ttt==0) {res = "T";} else if (ttt==1) {res = "B";} Else{res = "P";} System.out.println ("---------request:submitgameresult-------------"); Sendhttprequest ("{\" api_key\ ": \" Test "+i+" \ ", \" table_no\ ": \" a001\ ", \" computer_name\ ": \" computer001\ ", \" game_set\ ": \" "+i+" \ ", \" shoe_of_the_day\ ": \" "+i+" \ ", \" game_time\ ": \" "+new Date () +" \ ", \ "game_no\": \ "" +i+ "\", \ "active_game_no\": \ "" +i+ "\", \ "win\": \ "" +res+ "\", \ "win_type\": \ "\", \ "banker_pair\": \ "" + Randomutils.nextint (2) + "\", \ "player_pair\": \ "" "+randomutils.nextint (2) +" \ ", \" status\ ": \" 1\ "}", "/HTTP/ 127.0.0.1:8080/bdb/gameset!submitgameresult ", Constants.http_content_type_application_json); i++; System.out.println ("---------request:newgameset-------------") sendhttprequest ("{\" api_key\ ": \" test "+i+" \ ", \" Table_no\ ": \" a001\ ", \" computer_name\ ": \" computer001\ ", \" game_set\ ": \" +i+ "\", \ "shoe_of_the_day\": \ "" +i+ "\", \ " Game_time\ ": \" "+new Date () +" \ ", \" status\ ": \" 1\ "}", "Http://127.0.0.1:8080/bdb/gameset!newGameSet", constants.http _content_type_application_json);} t++;} /** * httpClient * @param reqstr * @param urlconfig * @param contentType * @return */private int sendhttprequest (String re Qstr,string urlconfig,string contentType) {try {Postmethod Postmethod = new Postmethod (urlconfig); Requestentity requestentity = new Stringrequestentity (reqstr,contenttype,constants.content_encoding_utF8);p ostmethod.setrequestentity (requestentity); HttpClient HttpClient = new HttpClient (); Httpclient.executemethod (Postmethod); Jsonresultmodel jsonresult= (Jsonresultmodel) Jsonobject.tobean (Jsonobject.fromobject ( Postmethod.getresponsebodyasstring ()), jsonresultmodel.class), int httpstatus = Integer.parseint ( Jsonresult.getstatus ()); return httpstatus;} catch (Exception e) {return 500;}} public static void Main (string[] args) {//random number 0 or 1for (int i = 0; i <; i++) {System.out.println (Randomutils.nextint (2) );}}}

The above is a scheduled task I customized, with httpclient constantly request the local environment of a project URL address, although there is no code to operate any database, but if you need to increase the demand one day, in the record each task request returned data please, and save in the database, or more requests to make appropriate operations, such as sending e-mail, this situation is more used to detect whether the server is functioning properly. Now that you want to manipulate the database, you will want to use the relevant DAO for crud, if you simply hit these lines in code:

@Autowiredprivate gamesetservice gamesetservice; @Autowiredprivate Gamesetdao Gamesetdao;

The guarantee is a null pointer, should not be managed here by the spring container, nature will not be injected, then how to solve it?

Many ways

People on the Internet how to get the IOC context, this is also very well understood, but the amount of code is more, if interested in understanding, can be the mother of the keyword "Web project to get Springbean"


My writing here is to introduce

Springbeanautowiringsupport.processinjectionbasedoncurrentcontext (this);
This is spring's automatic equipment, with the annotations in front of him will not be empty pointers, and the code is also beautiful, neat

If there is anything do not understand, we can leave a message or ask the degree Niang, anyway, I am also asked degrees Niang


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Using injection in non-spring containers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.