Retrieve Spring-managed beans in common classes and Spring beans

Source: Internet
Author: User

Retrieve Spring-managed beans in common classes and Spring beans

  1. Add the following classes to the project:

  

Import org. springframework. context. applicationContext; import org. springframework. context. applicationContextAware;/*** saves Spring ApplicationContext with static variables. ApplicaitonContext can be retrieved anywhere in the code. **/public class SpringContextHolder implements ApplicationContextAware {private static ApplicationContext applicationContext;/*** implements the context injection function of the ApplicationContextAware interface and saves it to static variables. */public void setApplicationContext (ApplicationContext applicationContext) {SpringContextHolder. applicationContext = applicationContext; // NOSONAR}/*** get ApplicationContext stored in static variables. */public static ApplicationContext getApplicationContext () {checkApplicationContext (); return applicationContext;}/*** retrieves beans from the static variable ApplicationContext and automatically converts them to the type of the assigned object. */@ SuppressWarnings ("unchecked") public static <T> T getBean (String name) {checkApplicationContext (); return (T) applicationContext. getBean (name);}/*** retrieves the Bean from the static variable ApplicationContext and automatically converts it to the type of the assigned object. * // @ SuppressWarnings ("unchecked") public static <T> T getBean (Class <T> clazz) {checkApplicationContext (); return (T) applicationContext. getBeansOfType (clazz);}/*** clear the static applicationContext variable. */public static void cleanApplicationContext () {applicationContext = null;} private static void checkApplicationContext () {if (applicationContext = null) {throw new IllegalStateException ("applicaitonContext is not injected, in applicationContext. springContextHolder ") ;}} defined in xml ");}}}

 2. Add the following to the spring configuration file:

<bean class="com.xxxxx.SpringContextHolder" lazy-init="false" />  

  3. Usage:

Spring contextholder. getBean ('xxxx') static method to get the spring bean object


Several Methods for Spring to obtain bean

However, for non-Spring framework management classes in the system, if you need to obtain Spring-managed classes, or, in the program, you need to dynamically obtain Bean instances based on Bean IDs, it is impossible to provide the setter method for all the Bean attributes required for this class first. Under such circumstances, there are many methods to obtain class instances managed by Spring framework. The following is a brief summary: method 1: Save the ApplicationContext object code during initialization: ApplicationContext ac = new FileSystemXmlApplicationContext ("applicationContext. xml "); ac. getBean ("beanId"); Note: This method is applicable to standalone applications using the Spring framework and requires the program to manually initialize Spring through the configuration file. Method 2: Use the tool class provided by Spring to obtain the ApplicationContext object code: 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"); Note: This method is suitable for B/S systems using the Spring framework, through ServletCo The ntext object gets the ApplicationContext object, and then obtains the required class instance through it. The difference between the two tools is that the former throws an exception when the acquisition fails, and the latter returns null. 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 (ApplicationContextcontext) method of this abstract class. Method 4: Inherit from abstract class WebApplicationObjectSupport Description: similar to the above method, call getWebApplicationContext () to obtain WebApplicationContext Method 5: Implement interface ApplicationContextAware Description: 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. The preceding method is applicable to different situations. Select the appropriate method based on the actual situation. It is worth mentioning that the classes used in the above method in the system are actually tightly coupled with the Spring framework, because these classes know that they are running on the Spring framework, therefore, this type of applications should be minimized in the system so that the system is as independent as possible from the current running environment and the required service provider should be obtained through DI as much as possible ....... Remaining full text>

How can I directly obtain the Bean in the Spring container through code?

[Citation] In the example of struts2 + spring, spring Bean can be used in applicationContext. add the following configuration in xml: <bean id = "springBean" scope = "prototype" class = "" <property name = "name" value = "chen"/</bean <bean id = "myAction" scope = "prototype" class = "" <property name = "springBean" ref = "springBean"/</bean if it is a j2ee application, when a web application is started, the ApplicationContext instance will be automatically loaded (the Spring container is responsible for creating Bean instances). Once the myAction of struts2 is instantiated, The SpringBean will be automatically injected, to use SpringBean. [Problem] But SpringBean still needs to be called through code: 1) for classes that are not created and managed by spring, for example, to create an object directly using new in java code, and I want to use SpringBean in this object. Because this object is not a class created and managed by the Spring container, even if it has the setter method, the springBean of the container will not be injected. 2) dynamically change the attribute value in spring bean. For example, the name value needs to be changed when the code is running. 3) define a non-Spring container creation and management class public class NonSpringClass implements ServletContextAware {private SpringBean springBean; // If testGetBean is not created and managed by the Spring container, even if it has the setter method, the springBean of the container will not be injected. Public void setSpringBean (SpringBean springBean) {this. springBean = springBean;} // use ApplicationContext to obtain springBean from the spring container; // Spring has two core interfaces: BeanFactory and ApplicationContext. ApplicationContext is the Child interface of BeanFactory, // they represent the Spring container. The Spring container is the factory that generates the Bean and is used to manage the Bean in the container. Public NonSpringClass () {// ApplicationContext acx = new ClassPathXmlApplicationContext ("applicationContext. xml "); ApplicationContext acx = new FileSystemXmlApplicationContext (" src/WEB-INF/applicationContext. xml "); springBean = (SpringBean) acx. getBean ...... remaining full text>

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.