SpringBoot study notes, three ways to get Spring Bean

We all know that when using the spring framework, if a class uses @Service and @Autowire to refer to other objects, in another class, only when the instance of this class is obtained through the IOC capacity of spring , those dependent objects can be correctly initialized, otherwise those dependent objects are null.

So there is a problem, how to get the bean in the spring ioc container (spring managed bean) in the ordinary class.

We all know that the context object ApplicationContext in spring is the basis for obtaining beans. In spring boot, we can obtain beans in the following three ways.

Related springboot learning videos:

https://www.bilibili.com/video/BV1XQ4y1m7ex

method one

Annotate @PostConstruct

The PostConstruct annotation is used on methods that need to be executed after dependency injection is complete to perform any initialization. This method must be called before putting the class into the service.

All classes that support dependency injection must support this annotation. Methods annotated with PostConstruct must be called even if the class does not request any resources to be injected. Only one method can be annotated with this annotation.

Methods applying the PostConstruct annotation must adhere to all of the following criteria:

  • The method must not have any parameters, except in the case of an EJB interceptor, as defined by the EJB specification, in which case it will take an InvocationContext object;
  • The return type of this method must be void;
  • The method must not throw checked exceptions;
  • The method of applying PostConstruct can be public, protected, package private or private;
  • Except for application clients, the method cannot be static;
  • The method can be final;
  • If the method throws an unchecked exception, the class must not be put into service unless it is an EJB that can handle and recover from the exception.
  • Spring Boot study notes, this one is too comprehensive!

way two

Start class ApplicationContext

Implementation method: In the startup class of springboot, define the static variable ApplicationContext, and use the getBean method of the container to obtain the dependent object. Recommend a Spring Boot basic tutorial and practical example: https://github.com/javastacks/javastack

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/**
 * @author: clx
 * @version: 1.1.0
 */
@SpringBootApplication
public class Application {
    public static ConfigurableApplicationContext ac;
    public static void main(String[] args) {
       ac = SpringApplication.run(Application.class, args);
    }
 
}

calling method

/**
 * @author: clx
 * @version: 1.1.0
 */
@RestController
public class TestController {
    /**
     * 方式二
     */
    @GetMapping("test2")
    public void method_2() {
        AutoMethodDemoService methodDemoService = Application.ac.getBean(AutoMethodDemoService.class);
        String test2 = methodDemoService.test2();
        System.out.println(test2);
    }
}

way three

Manually inject ApplicationContext

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 
 
/**
 * springboot静态方法获取 bean 的三种方式(三)
 * @author: clx
 * @version: 1.1.0
 */
@Component
public class StaticMethodGetBean_3<T> implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        StaticMethodGetBean_3.applicationContext = applicationContext;
    }
 
    public static <T> T  getBean(Class<T> clazz) {
        return applicationContext != null?applicationContext.getBean(clazz):null;
    }
}

calling method

/**
 * 方式三
 */
@Test
public void method_3() {
    AutoMethodDemoService autoMethodDemoService = StaticMethodGetBean_3.getBean(AutoMethodDemoService.class);
    String test3 = autoMethodDemoService.test3();
    System.out.println(test3);
}

I have tested all three methods above and they work perfectly.

Guess you like

Origin blog.csdn.net/f5465245/article/details/123551991