springboot 靜態方法注入bean、使用@value給static變量賦值


首先新建你的方法類: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去掉,這種方法也必須注意啟動類的掃描范圍。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM