项目结构如图所示,自定义的配置文件放在工程目录下,entry中是properties的注入实体类
新建一个实体类,用于注入配置文件的参数:
@Component
@PropertySource("classpath:MyProperties.properties")
public class MyProperties{
@Value("${myfield}")
private String myfield;
public void setCorpId(String myfield) {
DingTalkConfig.myfield = myfield;
}
public String getmyfield() {
return myfield;
}
}
@component表示将这个bean实例化spring的容器中
@PropertySource("classpath:xxx.properties")用来配置资源文件的路径
@Value("${myfield}")将资源文件中对应的值注入到bean中
老方法,将鼠标移动到@PropertySource的路径或@Value的值上,按住Ctrl键,若能跳到对应的资源文件则说明配置没有问题
值得注意的是:
如果你的bean中的值是static的,按照上面的方法是会注入的值就是null,要按照下面的方法配置:
@Component
@PropertySource("classpath:MyProperties.properties")
public class MyProperties{
private static String myfield;
@Value("${myfield}")
public void setCorpId(String myfield) {
DingTalkConfig.myfield = myfield;
}
public static String getmyfield() {
return myfield;
}
}
这样就不用担心因为static而注入失败了~