springboot 静态方法注入bean

首先新建你的方法类:DemoUtil

头部加注解:@Component

@Component
public class DemoUtil {
}

新增静态变量:

static DemoService demoService;

新增@Autowired的bean对象

@Autowired
DemoService demoServiceMapping;

注意这时候还是不能注入

新增@PostConstruct注解方法

@PostConstruct
public void init() {
    demoService = demoServiceMapping; 
}

 当然还需要注意的就是启动类的扫描范围:

不同包下可在启动类加上@ComponentScan配置扫描范围

猜你喜欢

转载自www.cnblogs.com/skyLogin/p/9233119.html