Parse how to obtain the bean configured in Spring in Java

Source: Internet
Author: User

This article provides a detailed analysis of how to obtain the bean configured in Spring in Java. For more information, see

1. What is Spring?
Spring is a lightweight container framework for IoC and AOP.

2. How can I obtain Spring-configured beans in a program?
Method 1: Save the ApplicationContext object during initialization
Code:

Copy codeThe Code is as follows:
ApplicationContext ac = new FileSystemXmlApplicationContex ("applicationContext. xml ");
Ac. getBean ("beanId ");


Note: This method is applicable to standalone applications using the Spring framework. You need to manually initialize Spring through the configuration file.

Method 2: Obtain the ApplicationContext object through the tool class provided by Spring.
Code:

Copy codeThe Code is as follows:
Import org. springframework. web. context. support. WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils
. GetRequiredWebApplicationContext (ServletContext SC)
ApplicationContext ac2 = WebApplicationContextUtils
. GetWebApplicationContext (ServletContext SC)
Ac1.getBean ("beanId ");
Ac2.getBean ("beanId ");


Method 3: inherit from the abstract class ApplicationObjectSupport
Description: The abstract class ApplicationObjectSupport provides the getApplicationContext () method to conveniently obtain ApplicationContext. During Spring initialization, The ApplicationContext object is injected through the setApplicationContext (ApplicationContext context) method of this abstract class.

Method 4: inherit from the abstract class WebApplicationObjectSupport
Note: method 3 is similar. Call getWebApplicationContext () to obtain WebApplicationContext.

Method 5: implement the ApplicationContextAware Interface
Note: implement the setApplicationContext (ApplicationContext context) method of this interface and save the ApplicationContext object. During Spring initialization, The ApplicationContext object is injected using this method.

Related Article

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.