How to set the attributes to a generic @Service class in Spring Boot?

Viewed 1169

I'm new to Spring Boot, so bare me with my basic question here.

I want to build a generic @Service class that has well defined methods that don't even need to be overwritten.

The only thing this class needs is to adjust its attributes based on which Controller method was called. Basically, this class works as a Job handler that needs to adjust some parameters so its methods can perform what they're supposed to compute. The job will always have the same workflow, calling the methods in the same order, but it will obtain different results depending on the parameters/attributes it receives, which, as I said before, are defined by the controller methods.

The only attribute it has beside the ones that adjust the job's workflow is an autowired @Repository object that will save the results of the job in a database.

Maybe I could simply instantiate an Job Handler object and call a constructor with the paramaters I need for the job, but I don't know what is the "Spring way" of doing this, considering how Spring works with dependency injection and I need a @Repository object embbeded into the Job Handler service.

I would really appreciate if anyone could write a sample code/example so I could understand how this can be done with Spring Boot so I don't have to duplicate code or Service Classes.

1 Answers

The Spring way for this case would be to create a Bean of your JobHandler, where you inject the necessary dependencies, like your Repository:

@Configuration
class MyConfiguration {

    @Bean
    MyJobHandler myJobHandler(MyRepository myRepository) {
        return new MyJobHandler (myrepository);
    }

}

Alternatively, if you do not want a configuration class, you could declare your JobHandler as a Component and inject the repository in the constructor:

@Component
class MyJobHandler {

    private MyRepository myRepository;

    public MyJobHandler myJobHandler(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

}
Related