Spring Boot————静态方法如何调用Spring容器中的Bean

问题分析

在使用静态方法的时候,某些情况下,需要使用类似自动注入的Bean来实现某些业务逻辑。

一般的非静态方法,可以很容易的通过在方法所在的类中@Autowired自动将依赖的Bean注入到本类中,并操作。

静态方法在使用同样的操作流程时,由于静态调用的约束,需要在@Autowired注入时,将Bean对象设置为是static。然而在调用时却发生“空指针”异常。代码如下:

Service类:


调用类:


为什么会出现这种情况?原因是Spring容器的依赖注入是依赖set方法,而set方法是实例对象的方法,而静态变量属于类,因此注入依赖时无法注入静态成员变量,在调用的时候依赖的Bean才会为null。

解决方案

spring容器注入静态变量的方法并不唯一,但是springboot对spring容器有一定的托管处理,很多配置属于默认最优配置,因此,在springboot中,此问题最简单的解决方案就是通过getBean的方式。

总体思路是:在springboot的启动类中,定义static变量ApplicationContext,利用容器的getBean方法获得依赖对象。

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("-----------------------启动完毕-------------------------");
	}
}

修改调用方式:

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();
    }
}

测试:



猜你喜欢

转载自blog.csdn.net/u014745069/article/details/80087944