步骤:
第一步编写配置类:
第二步:将配置文件映射到实体类
@Configuration
@PropertySource(value = "classpath:config.properties")
public class CustomConfig {
@Value("${server.host}")
private String host;
@Value("${server.port}")
private int port;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
第三步:从实体类获取值
VideoServiceImpl:
@Service("videoService")
public class VideoServiceImpl implements VideoService {
@Autowired
private CustomConfig customConfig;
public int save(Video video) {
System.out.println("保存Video");
return 1;
}
public Video findById(int id) {
System.out.println("根据id找视频");
System.out.println(customConfig.getHost());
return new Video();
}
}
测试代码:
public class App {
public static void main(String[] args){
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
//扫描指定的包,包括子包
context.scan("work.yspan");
//里面完成初始化操作,核心方法
context.refresh();
VideoService videoService=(VideoService) context.getBean("videoService");
videoService.findById(54);
}
}
测试效果截图: