Get Spring ApplicationContext object

Source: Internet
Author: User

This method is very slow in Initialization. ApplicationContext context = new ClassPathXmlApplicationContext (); at that time, I felt that this was unnecessary and wasted memory. Then I finally came up with a solution. For your reference, I hope to help you.


The code I wrote is as follows:

01
Package com. task. common;
02
 
03
Import java. util. Locale;
04
Import org. springframework. beans. BeansException;
05
Import org. springframework. context. ApplicationContext;
06
Import org. springframework. context. ApplicationContextAware;
07
/**
08
* Obtain the Spring context and Internationalization
09
* @ Author bingchuan --> www.vijun.com
10
*
11
*/
12
Public final class SpringContextUtil implements ApplicationContextAware {
13
Private static ApplicationContext context;
14

15
@ SuppressWarnings ("static-access ")
16
Public void setApplicationContext (ApplicationContext contex) throws BeansException {
17
This. context = contex;
18
}
19
Public static Object getBean (String beanName ){
20
Return context. getBean (beanName );
21
}
22

23
Public static String getMessage (String key ){
24
Return context. getMessage (key, null, Locale. getDefault ());
25
}
26
}


You can obtain ApplicationContext and international content as follows:
1. initialize www.2cto.com in the spring configuration file.
1
<Bean class = "com. task. common. SpringContextUtil" id = "springContextUtil"/>

2. Use

1
JdbcTemplate jdbcTemplate = (JdbcTemplate) SpringContextUtil. getBean ("jdbcTemplate ");


Author: ye luhua Kai

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.