Recommendation of a way for SpringBoot ordinary classes to call Bean objects

  • 2021-12-12 08:25:20
  • OfStack

Directory SpringBoot common class calls Bean object SpringBoot use of bean

The SpringBoot ordinary class calls the Bean object

Sometimes we have a special need to call a method of an bean object managed by Spring in a common class not managed by Spring, for example, an SpringMVC project passed in controller


@Autowired
private TestService testService;

By injecting the TestService interface, you can call the method of this interface to implement the class.

However, it is obviously impossible to do this in a general class. The injected TestService will report a null pointer exception, and you can't get this bean. In a general ssm project, we can set the general class as an bean object through xml configuration, so TestService is valid, or TestService can be obtained by directly reading bean in xml configuration with ApplicationContext. `

Spring Boot has abandoned all kinds of tedious xml configuration, of course, it no longer uses xml configuration. I saw a very simple way on the Internet before, but now I can't find a link. Make a record here.

Define ApplicationContext static variables and set methods in ordinary classes


    private static ApplicationContext applicationContext;// Startup class set Enter, call the following set Method 
    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

In the startup class, the ConfigurableApplicationContext object has already been generated at startup, and ConfigurableApplicationContext is the implementation of ApplicationContext interface, which is directly passed to the setApplicationContext method of ordinary class


@SpringBootApplication
@ServletComponentScan
public class WxApplication implements EmbeddedServletContainerCustomizer{
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(WxApplication.class, args);
        TestClass.setApplicationContext(applicationContext);
    }
}

Because it is a static variable, applicationContext already exists when the class is loaded, and TestService can be obtained. The only bad thing is that the static variable will exist directly after the server starts


public class TestClass {
    private static ApplicationContext applicationContext;// Startup class set Enter, call the following set Method 
    public static void setApplicationContext(ApplicationContext context) {
        // TODO Auto-generated method stub
        applicationContext = context;
    }
    public void getBeanTest(){
        TestService testService  = (TestService)applicationContext.getBean(TestService.class);
    }
}

Additional:

In the common Spring project will be started through org. springframework. web. context. ContextLoaderListener listener from the loading system resources and management of bean, WebApplicationContextUtils tool class provided by Spring can be requested to get the bean of the runtime project, if you look at the source code, you can know the listener execution and WebApplicationContextUtils class association


// Encapsulation 1 Under, the of the class class And requests request Is a required parameter 
public static <T> T getBean(Class<? extends Object> cla,HttpServletRequest request){
        if(request == null){
            return null;
        }
        return (T)WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(cla);//getBean Parameters can be bean Class .class Or directly bean Adj. Id
    }
// Get in this way bean
TestService testService= (TestService)getBean(TestService.class, request);

Application of bean in SpringBoot

Usually, there are three ways to define bean, such as annotations and definitions in xml files

However, when defining bean in the form of annotations, if we do not specify a name for bean, spring itself will also specify a default name for bean, and the naming rules are as follows:

1. If the first two letters of the class are capitalized, the name of bean is the name of the class. For example, if the name of the class is BEan, the name of bean is BEan.

2. If the class name is only uppercase, the name of bean will become lowercase. For example, if the name of the class is Bean, the name of bean is bean

Use of bean in Springboot

Many times, when we develop web projects of spring, boot and other related spring, there are several ways to use bean:

1. Introduce bean through the autowired field, so that bean can be used

2. In the program, one bean is obtained by ApplicationContext of spring to operate

@Autowired Bean bean;

As for the first type, our form is quite common. Usually, after autowired references bean in this way, the corresponding method can be called directly through the object name bean

For the second type, 1 is called directly through the bean name


Related articles: