0

I have a userService file which includes this code:

    package com.example.demo.services;

    import com.example.demo.entity.User;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.stereotype.Service;

    import java.io.IOException;
    import java.util.List;
    import java.util.concurrent.atomic.AtomicReference;

    @Service
    public class UserService {

        public static AtomicReference<UserService> INSTANCE = new AtomicReference<UserService>();
        public static List<User> userList  ;

        public UserService() throws IOException {
            final UserService previous = INSTANCE.getAndSet(this);

            userList = new ObjectMapper().readValue(
                    new ClassPathResource("db/user.json").getFile(),
                    new ObjectMapper().getTypeFactory().constructCollectionType(List.class, User.class));
            if(previous != null)
                throw new IllegalStateException("Second singleton " + this + " created after " + previous);
        }

        public static UserService getInstance() {
            return INSTANCE.get();
        }

    }

In this Service I am loading a JSON file into the variable userList and the JSON file is stored in src/main/resources/db/user.json. This works fine in the IDE. But when I creates a Jar file either via Intellij or manually, the db/user.json is stored in BOOT-INF/classes/db/user.json (inspected via this command: jar tf backend.jar).

The Docker Image could not get started as it could not find the file. So how would I change this so that it should work both in normal debug and Docker image?

To be noted, userList converts the JSON file in the List.

Yunus
  • 405
  • 5
  • 18
  • The answer to this other post might help - https://stackoverflow.com/questions/25869428/classpath-resource-not-found-when-running-as-jar. TLDR - "resource.getFile() expects the resource itself to be available on the file system, i.e. it can't be nested inside a jar file...." – Tim Tong Jan 31 '22 at 01:57
  • Yeah, I got it. Thanks. Solved the problem actually based on the answer. – Yunus Jan 31 '22 at 18:05

0 Answers0