简体   繁体   中英

How to transfer a list of strings from a file to property of application.properties (using Spring boot 2.3.x)

I have a application.yaml

app:
  list: /list.txt
  • list.txt

Also I have a file with list of strings. It locates into /resources(in the root /resource).

first
second
third
  • class
public class Bean{

@Value("${app.list}")
private List<String> listProp = new ArrayList<>();

public void print(){
 System.out.println(listProp);
}

}

I have found that:

public class ResourceReader {

    public static String asString(Resource resource) {
        try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) {
            return FileCopyUtils.copyToString(reader);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public static String readFileToString(String path) {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource(path);
        return asString(resource);
    }
}
@Configuration
public class ConfigurationResource {
    
@Configuration
public class ConfigurationResource {

    @Value("${app.list}")
    private String pathToFile;

    @Bean
    public List<String> resourceString() {

        String blackList = ResourceReader.readFileToString(pathToFile);
        return List.of(blackList.split("\n"));

    }
}
}
@RequiredArgsConstructor
public class HelloController {

 
    private final List<String> resourceString;
...
}

This is necessary in order not to manually write a list of strings to the property app.name (there are several hundred lines).

However, I find it difficult to figure out how to do it at low cost. So that it can be easily maintained.

maybe there is an easier way? I would not like to add a hardcoding value in the configuration class

Maybe someone has some ideas?

Here is the solution from my understanding if you have to keep lines in the text file that you've shared:

public class Bean {

    @Value("${app.list}")
    private String listProp; // only get name of file

    public void print(){
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream is = classLoader.getResourceAsStream(listProp);
        StringBuilder sb = new StringBuilder();
        try {
            for (int ch; (ch = is.read()) != -1; ) {
                sb.append((char) ch);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(sb);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM