8 ways to get beans from Spring, very practical!

This article will introduce 8 ways to get beans from the Spring IOC container!

1. Save the ApplicationContext object during initialization

Standalone applications for the Spring framework require the program to initialize Spring through a configuration file.

applicationContext.xmlConfiguration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="test" class="com.sxtx.bean.Test">
</bean>

</beans>

code:

@Test
public void test() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    //ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml"); 
    Test test= (Test) applicationContext.getBean("test");
    System.out.println(test);
}

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

It is suitable for the B/S system of the Spring framework, and ServletContextobtains ApplicationContextobjects through objects. Then get the required class instance through it. The difference between the following two tool methods is that the former throws an exception when the acquisition fails. The latter returns null.

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); 
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); 
ac1.getBean("beanId"); 
ac2.getBean("beanId");  

3. Implement the interface ApplicationContextAware (recommended)

Implement setApplicationContext(ApplicationContext context)the method of this interface and save ApplicationContextthe object. When Spring is initialized, the class is scanned, and ApplicationContextthe object will be injected through this method. Then you can get the spring container bean in the code.

For example:

User bean = SpringUtils.getBean(“user”);
@Component
public class SpringUtils implements ApplicationContextAware {
 
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }
 
    public static <T> T getBean(String beanName) {
        if(applicationContext.containsBean(beanName)){
            return (T) applicationContext.getBean(beanName);
        }else{
            return null;
        }
    }
 
    public static <T> Map<String, T> getBeansOfType(Class<T> baseType){
        return applicationContext.getBeansOfType(baseType);
    }
}

4. Inherited from the abstract class ApplicationObjectSupport

Call the method of the parent class getApplicationContext()to obtain the Spring container object.

@Service
public class SpringContextHelper extends ApplicationObjectSupport {

    public Object getBean(String beanName) {
        return getApplicationContext().getBean(beanName);
    }
}

5. Inherited from the abstract class WebApplicationObjectSupport

call getWebApplicationContext()getWebApplicationContext

@Service
public class SpringContextHelper extends WebApplicationObjectSupport {

    public Object getBean(String beanName) {
        return getApplicationContext().getBean(beanName);
    }
}

6. Use BeanFactory to obtain directly (not recommended)

Use to BeanFactoryobtain Bean instances directly from the factory, but XmlBeanFactorythe class has been deprecated, so it is not recommended to use.

@Test
public void test() {
    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
    Test test= (Test) beanFactory.getBean("test");
    System.out.println(test);
}

7. Use the getCurrentWebApplicationContext method provided by ContextLoader

@Test
public void test() {
    MockServletContext sc = new MockServletContext("");
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/applicationContext.xml");
    ServletContextListener listener = new ContextLoaderListener();
    ServletContextEvent event = new ServletContextEvent(sc);
    listener.contextInitialized(event);
    
    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    Test test= (Test) wac.getBean("test");
    System.out.println(test);
}

8. Implement the interface BeanFactoryPostProcessor

The spring tool class is convenient for obtaining beans in a non-spring management environment

@Component
public final class SpringUtilsS implements BeanFactoryPostProcessor
{
    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
    {
        SpringUtilsS.beanFactory = beanFactory;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException
    {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取类型为requiredType的对象
     *
     * @param clz
     * @return
     * @throws BeansException
     *
     */
    public static <T> T getBean(Class<T> clz) throws BeansException
    {
        T result = (T) beanFactory.getBean(clz);
        return result;
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     *
     * @param name
     * @return boolean
     */
    public static boolean containsBean(String name)
    {
        return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     *
     * @param name
     * @return boolean
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.isSingleton(name);
    }

    /**
     * @param name
     * @return Class 注册对象的类型
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名,则返回这些别名
     *
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.getAliases(name);
    }

    /**
     * 获取aop代理对象
     * 
     * @param invoker
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker)
    {
        return (T) AopContext.currentProxy();
    }
}

expand

BeanFactoryand ApplicationContextare the two core interfaces of Spring, both of which can be used as Spring containers. where ApplicationContextis BeanFactorythe subinterface of .

BeanFactory

(1) It is the bottom interface (the most original interface) in Spring, which includes the definition of various beans, reads the bean configuration document, manages the loading and instantiation of the bean, controls the life cycle of the bean, and maintains the relationship between the bean dependencies.

(2) The bean is injected in the form of lazy loading, that is, only when a bean is used (called getBean()), the bean is loaded and instantiated. In this way, we cannot find some existing Spring configuration problems. If a certain property of the Bean is not injected, BeanFacotryafter loading, an exception will not be thrown until the getBean method is called for the first time.

(3) BeanFactoryUsually created programmatically.

(4) BeanFactoryand ApplicationContextboth support the use BeanPostProcessorof BeanFactoryPostProcessor, but the difference between the two is: BeanFactorymanual registration is required, but ApplicationContextautomatic registration.

(5) Small memory usage.

ApplicationContext

1. ApplicationContextAs a derivative of the interface BeanFactory, in addition to providing BeanFactorythe functions it has, it also provides a more complete framework function:

  • Inheritance MessageSource, thus supporting internationalization.

  • Unified resource file access method.

  • Provides events to register beans in listeners.

  • Load multiple configuration files at the same time.

  • Load multiple (inherited) contexts, each dedicated to a specific layer, such as the web layer of the application.

2. ApplicationContext, it creates all beans at once when the container starts. In this way, when the container starts, we can find configuration errors in Spring, which is beneficial to check whether the dependent properties are injected. ApplicationContextPreload all single-instance beans after startup. By preloading single-instance beans, you can ensure that when you need them, you don't have to wait because they have already been created.

3. ApplicationContextIt takes up a lot of memory space. When the program has a lot of configuration beans, the program starts slowly.

4. ApplicationContextIt can be created programmatically or in a declarative way, such as using ContextLoader.

 

Guess you like

Origin blog.csdn.net/2301_77463738/article/details/131490351