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