网站建设微信公众号小程序制作,营销网站制作公司,重庆做商城网站,wordpress盈利博客问题分析
在使用静态方法的时候#xff0c;某些情况下#xff0c;需要使用类似自动注入的Bean来实现某些业务逻辑。
一般的非静态方法#xff0c;可以很容易的通过在方法所在的类中Autowired自动将依赖的Bean注入到本类中#xff0c;并操作。
静态方法在使用同样的操作流…问题分析
在使用静态方法的时候某些情况下需要使用类似自动注入的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();}
}测试