Spring actively acquires beans through ApplicationContext

Source: Internet
Author: User
Tags lowercase

Original address:

http://blog.csdn.net/jinzhencs/article/details/51673782

Question 1:
There is an asynchronous thread runnable that requires DAO and cannot be passed in autowired and compoment annotations.
So I want to take the initiative to get the bean through spring context.

Question 2:
Getbean (name) gets failed.
Solve:
Default DAO's Name= class name (first letter lowercase)
For example:
Interface Name: Templatedao getname ("Templatedao") can be a generic springcontextutil get Bean 1. Implementing the Applicationcontextaware Interface

/** * Spring Context configuration * @author mingchenchen * */@Component public class Springcontextutil implements Applicationcontexta
    Ware {private static Logger Logger = Logger.getlogger (Springcontextutil.class);

    private static ApplicationContext ApplicationContext = null; public void Setapplicationcontext (ApplicationContext applicationcontext) throws Beansexception {Logger.info ("
        ------springcontextutil setapplicationcontext-------");
    Springcontextutil.applicationcontext = ApplicationContext;
    } public static ApplicationContext Getapplicationcontext () {return applicationcontext;  }/** * Note Bean name default = Class name (first letter lowercase) * For example: A8sclusterdao = Getbean ("K8sclusterdao") * @param name *
        @return * @throws beansexception */public static Object Getbean (String name) throws Beansexception {
    return Applicationcontext.getbean (name);
   /** * Get to Bean * @param <T> * @param clazz based on class name  * @return * @throws beansexception */@SuppressWarnings ("unchecked") public static <T> T Getbean ByName (class<t> clazz) throws Beansexception {try {char[] cs=clazz.getsimplename (). ToCharArray
            ();
        Cs[0] + = 32;//First letter uppercase to lowercase return (T) Applicationcontext.getbean (string.valueof (CS));
            } catch (Exception e) {e.printstacktrace ();
        return null;
    }} public static Boolean Containsbean (String name) {return Applicationcontext.containsbean (name); public static Boolean Issingleton (String name) throws Nosuchbeandefinitionexception {return Applicationco
    Ntext.issingleton (name);
 }

}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 2 8 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 2. Configure the load SP in Web. xml The listener of the ring container
<!--initialize the spring container so that the spring container starts automatically with the launch of the Web App-  
    <listener>  
        <listener-class> Org.springframework.web.context.contextloaderlistener</listener-class>  
    </listener>  
1 2 3 4 1 2 3 4

Getbeanbyname (Class clazz)
This method is better to use, but note that DAO and Service Impl need to be configured with the name @service ("MyService").
The rule is the first letter of the class name for the interface service lowercase. The second way:

Now do a system initialization of the East Systeminit, and then found that the above Getbean () can not be used. The discovery is because Springcontextutil has not been initialized at the time of the system initialization, resulting in something Getbean () failing in the Systeminit class.
So small modified, put Applicationcontextaware in the Systeminit class, and then injected into the springcontextutil, so that the implementation of the system initialization method, ApplicationContext must not be null.

/** * Spring Context configuration * @author Mingchenchen * */public class Springcontextutil {private static Logger Logger = Logg

    Er.getlogger (Springcontextutil.class);
    @Autowired it would be better to follow Springtest's approach.
    ApplicationContext CTX;

    private static ApplicationContext ApplicationContext = null; public static void Setapplicationcontext (ApplicationContext applicationcontext) throws Beansexception {Logger.inf
        O ("------springcontextutil setapplicationcontext-------");
    Springcontextutil.applicationcontext = ApplicationContext;
    }//Note here becomes static public static ApplicationContext Getapplicationcontext () {return applicationcontext;
     }/** * Note Bean name default = Class name (first letter lowercase) * For example: A8sclusterdao = Getbean ("K8sclusterdao") * @param name
        * @return * @throws beansexception */public static Object Getbean (String name) throws Beansexception {
    return Applicationcontext.getbean (name); }/** * Get to be based on class namean * @param <T> * @param clazz * @return * @throws beansexception */@SuppressWarnings (
            "Unchecked") public static <T> T getbeanbyname (class<t> clazz) throws Beansexception {try {
            Char[] Cs=clazz.getsimplename (). ToCharArray ();
        Cs[0] + = 32;//First letter uppercase to lowercase return (T) Applicationcontext.getbean (string.valueof (CS));
            } catch (Exception e) {e.printstacktrace ();
        return null;
    }} public static Boolean Containsbean (String name) {return Applicationcontext.containsbean (name); public static Boolean Issingleton (String name) throws Nosuchbeandefinitionexception {return Applicationco
    Ntext.issingleton (name);
 }

}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 4 4 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
/** * Descripties: System initialization * @author wangkaiping * May 23, 2016 morning 11:58:09 * * @Component public class Systeminit implement
    s initializingbean,applicationcontextaware{private static Logger Logger = Logger.getlogger (Systeminit.class);

    @Autowired private Clusterdao Clusterdao; @Override public void Afterpropertiesset () throws Exception {logger.info ("--------------system initialization---------------
        ----");
        Initclustercache ();//initialization of the cluster data must begin with the Initrefreshappstatustask ();
        Initupdateappstatustodb ();
        Initupdatesession ();
    Logger.info ("--------------system initialization completed-------------------"); }/** * 1. Initialize cluster data */private void Initclustercache () {Logger.info ("1. Initialize the cluster information into the cache: Clustercache start
        "); Querying the database for all cluster data list<clusterentity> allclusterinfolist = Clusterdao.selectall (Clusterentity.class, "Delete_fl
        Ag=0 "); for (clusterentity k8sclusterentity:allclusterinfolist) {clustercache.put (k8sClusterentity.getuuid (), k8sclusterentity);//cache} logger.info ("1. Initialize the cluster information into the cache: Clustercache complete, total" + ALLCL
    Usterinfolist.size () + "bar data"); }/** * 2. Initialize asynchronous task: Refresh all app states */private void Initrefreshappstatustask () {Logger.info ("2. Initialization task: Re
        Freshallappstatustask Refresh the pod status of the k8s under application and deposit to the queue to be updated ");
        Refreshappstatusexcutor.init ();
    Logger.info ("2. Initialization task: Refreshallappstatustask complete"); }/** * 3. Initialize asynchronous task: Update state to database */private void Initupdateappstatustodb () {Logger.info ("3. Initialization task: REF
        Reshtodbtask remove data from the Appinstance queue to be updated and update the database ");
        Updateappstatustodbexcutor.init ();
    Logger.info ("3. Initialization task: Refreshtodbtask complete"); }/** * 4.
        Initialize asynchronous task: Update all sessions of the user */private void Initupdatesession () {Logger.info ("4. Initialization task: Update session start");
        Usersessionupdateexcutor.init ();
    Logger.info ("4. Initialize task: Update session End"); }//////////////////////////////////////////////////////////////////ThisMethod must not be written as static @Override public void Setapplicationcontext (ApplicationContext applicationcontext)
        Throws Beansexception {//actually put ApplicationContext into the Springcontextutil
    Springcontextutil.setapplicationcontext (ApplicationContext); }}

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.