Spring Boot——How to call Beans in Spring container from static methods

problem analysis

When using static methods, in some cases, it is necessary to use beans similar to automatic injection to implement some business logic.

For general non-static methods, it is easy to automatically inject dependent beans into this class by @Autowired in the class where the method is located, and operate.

When static methods use the same operation process, due to the constraints of static invocation, it is necessary to set the Bean object to be static when @Autowired is injected. However, a "null pointer" exception occurs when calling. code show as below:

Service class:


calling class:


Why does this happen? The reason is that the dependency injection of the Spring container depends on the set method, and the set method is the method of the instance object, and the static variable belongs to the class, so the static member variable cannot be injected when the dependency is injected, and the dependent bean will be null when it is called.

solution

The method of injecting static variables into the spring container is not unique, but springboot has a certain management process for the spring container, and many configurations belong to the default optimal configuration. Therefore, in springboot, the easiest solution to this problem is to use getBean.

The general idea is: in the startup class of springboot, define the static variable ApplicationContext, and use the getBean method of the container to obtain the dependent object.

package com.mht;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories
public class Start {
    private static Logger logger = LoggerFactory.getLogger(Start.class);
    public static ConfigurableApplicationContext ac;

	public static void main(String[] args) {
	    Start.ac = SpringApplication.run(Start.class, args);
		logger.info("----------------------Startup complete-------------------- -----");
	}
}

Modify the calling method:

package com.mht.utils;

import com.mht.Start;
import com.mht.service.SimpleService;

public class Utility {
    public static void callService() {
        Start.ac.getBean(SimpleService.class).testSimpleBeanFactory();
    }
}

test:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325530504&siteId=291194637