Java gets spring's beans

Source: Internet
Author: User

/**
* Load Spring configuration file, provide Getbean interface.
* @author Xiongzy
*
*/
Public final class Beanlocator {
private static final Logger Logger = Logger.getlogger (Beanlocator.class);
/**
* Single instance.
*/
private static Beanlocator instance = NULL;

/**
* Default configuration file name.
*/
private static final String Default_configuration_filename = "Spring/applicationcontext.xml";

/**
* Load the profile name.
*/
private static String configurationfilename = null;

/**
* Spring environment.
*/
Private ApplicationContext applicationcontext = null;

/**
* Singleton mode.
* @return Interface
*/
public static Beanlocator getinstance () {
if (instance = = null) {
Synchronization control code to prevent initialization multiple times.
Synchronized (logger) {
if (instance = = null) {
Instance = new Beanlocator ();
}
}
}
return instance;
}

/**
* Set the profile name.
* @param filename configuration file name
*/
public static void Setconfigurationfilename (String fileName) {
Configurationfilename = FileName;
}


/**
* Private construction.
*/
Private Beanlocator () {
if (Configurationfilename = = NULL | | configurationfilename.length () = = 0) {
Configurationfilename = Default_configuration_filename;
}
Get the Spring Framework bean environment
try{
ApplicationContext = new Classpathxmlapplicationcontext (configurationfilename);
}catch (Exception e) {
Logger.error ("Exception occurred while initializing spring configuration file:" + e.getmessage (), E);
throw new RuntimeException ("Exception occurred while initializing spring configuration file:" + e.getmessage (), E);
}
}

/**
* Spring Getbean interface.
* @param beanname Interface Name
* @return Interface
*/
Public Object Getbean (String beanname) {
Return Applicationcontext.getbean (Beanname);

}

public static void Main (string[] args) {
Cityinfoservice Cityinfoservice = (cityinfoservice) beanlocator.getinstance (). Getbean ("CityInfoService");
System.out.println (Cityinfoservice);
}

}

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.