使用场景: 有时候需要再配置类Configuration中动态获取配置文件properties中的自定义值
缺点: 该方式只能读取类路径下的配置文件
**案例:**创建一个自定义参数的线程池,参数从配置文件中获取
@Configuration public class MyThreadConfig { @Bean public ThreadPoolExecutor threadPool(){ Properties properties = new Properties(); // 使用ClassLoader加载properties配置文件生成对应的输入流 InputStream in = MyThreadConfig.class.getClassLoader().getResourceAsStream("config.properties"); // 使用properties对象加载输入流 try { properties.load(in); return new ThreadPoolExecutor(new Integer(properties.getProperty("coreSize")), new Integer(properties.getProperty("maxSize")), new Long(properties.getProperty("keepAliveTime")), TimeUnit.SECONDS, new LinkedBlockingDeque<>(100000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } catch (IOException e) { e.printStackTrace(); } return null; } }这个依赖会只会产生编码时提示,不导入也可以
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency>