首先新建你的方法类:DemoUtil

头部加注解:@Component

@Component
public class DemoUtil {
}

新增静态变量:

static DemoService demoService;

新增@Autowired的bean对象

@Autowired
DemoService demoServiceMapping;

注意这时候还是不能注入

新增@PostConstruct注解方法

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

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

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

 

properties 属性引入

假若在properties文件中配置如下属性:project.author

之前有写到用@value

那么在静态方法中怎么引入呢,直接@value是不可以的,一下介绍两种方法

第一种:如上文注入bean方式,在@PostConstruct方法中配置使用

第二种:

public static String springProfilesActive;

@Value(value = "${spring.profiles.active}")
public void setSpringProfilesActive(String springProfilesActive) {
    SystemConfig.springProfilesActive = springProfilesActive;
}

使用set方法赋值,set方法static去掉,这种方法也必须注意启动类的扫描范围。

相关文章:

  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
  • 2022-02-09
  • 2022-12-23
  • 2021-08-09
  • 2022-12-23
  • 2021-09-22
猜你喜欢
  • 2021-04-28
  • 2021-07-12
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案