Rüdiger
Rüdiger

Reputation: 943

How to use services within a singleton-class Spring Boot (wire up different services with a "usual" class)

I want to run a few tests for my Spring-Boot application and I keep running into a NullPointerException within a singleton. I have the following setup:

@Service
public class ProjectServiceImpl implements ProjectService {
    @Transactional
    @Override
    public void saveProject(ProjectDto projectDto) {        
        ProjectEntity projectEntity = ProjectConverter.getInstance().convertDtoToEntityWithDefaultFactory(projectDto);
        entityManager.persist(projectEntity);
        entityManager.flush();
    }
}

And the following Singleton:

@ComponentScan(myServicePackageImpl)
public class ProjectConverter {

    private static ProjectConverter projectConverterInstance;

    @Autowired
    private FactoryEntityService factoryService;

    public static ProjectConverter getInstance() {
        if (projectConverterInstance == null) {
            projectConverterInstance = new ProjectConverter();
        }
        return projectConverterInstance;
    }

    private ProjectConverter() {
    }

    @Transactional
    public ProjectEntity convertDtoToEntityWithDefaultFactory(ProjectDto projectDto) {
        FactoryEntity defaultFactory = this.factoryService.
                getDefaultFactoryEntity();
    //...
    }
}

Now I read this article that said that you might run into a NullPointerException if you instantiate your class manually (which I am doing in the singleton) - now my question: How can I workaround that? I got my Converter Class that needs to be some database-stuff which can be done within another Service. For me that means that I cannot only have static members in my class (since I use Autowired services). Is it even possible to wire up two services in a "usual class"?

Upvotes: 1

Views: 821

Answers (1)

ninja.coder
ninja.coder

Reputation: 9658

Now I read this article that said that you might run into a NullPointerException if you instantiate your class manually (which I am doing in the singleton).

You don't have to initialize the ProjectConverter by yourself. You can just mark it as @Component and Spring shall create a Bean of this class for you.

Code Snippet:

@Component
public class ProjectConverter { ... }

Upvotes: 2

Related Questions