Home > Java > javaTutorial > body text

What are the ways to obtain beans in Spring Boot?

WBOY
Release: 2023-05-12 15:22:06
forward
1970 people have browsed it

We all know when using the spring framework that if a class uses @Service, @Autowire, this dependency injection method references other objects, in another class, this class can only be obtained through spring's IOC weight. Only when there is an instance, the dependent objects can be correctly initialized, otherwise the dependent objects are null.

So there is a question, how to get the beans in the spring ioc container (spring managed beans) in ordinary classes.

We all know that the ApplicationContext context object in spring is the basis for obtaining beans.

In spring boot, we can obtain Beans in the following three ways.

Method 1 Annotation @PostConstruct

What are the ways to obtain beans in Spring Boot?

The PostConstruct annotation is used on methods that need to be executed after dependency injection is completed to perform any initialization. This method must be called before placing 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 comply with all of the following standards:

The method must not have any parameters, except in the case of an EJB interceptor (interceptor), as defined by the EJB specification. In this case it will have an InvocationContext object;
The return type of this method must be void;
This method must not throw a checked exception;
The method 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 the service , unless it is an EJB that can handle exceptions and recover from them.

Method 2 Startup class ApplicationContext

Implementation method: In the springboot startup class, define the static variable ApplicationContext, and use the getBean method of the container to obtain the dependent object.

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);
    }
 
}
Copy after login

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);
    }
}
Copy after login

Method 3 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;
    }
}
Copy after login

Calling method

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

The above is the detailed content of What are the ways to obtain beans in Spring Boot?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template