Search code examples
javaspringspring-bootspring-annotations

how to configure service and repository classes spring boot


@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Repository:

@Repository
public interface FileRepository { }


public class FileRepositoryImpl implements FileRepository {}

Service and Impl:

@Service
public interface FileService { }


public class FileService implements FileService {

@Autowired 
FileReposiory repo;

}

TasK:

@Component
public class DummyTask  {

    @Autowired
    private FileService fileService;



    public void run(String schedule) {
        fileService.runtask(schedule);
    }
}

I am trying to run a simple application using the annotations above. This application has no REST endpoint or use a controller. My fileService has null reference when executing DummyTask.

Also, when I am running the Junit test to test the FileRepository, I also get fileRepository as null. Could someone please point out how it is unsatisfied and how to correct?

public class FileRepositoryTest {

    @Autowired
    private FileRepository fileRepository;


    @Test
    public void testGetCustomerDir() {

       //blah    
    }
}

I Execute my task as follows:

 threadPoolTaskScheduler.schedule(new Job(reportSchedule), new CronTrigger(reportSchedule.getCronExpression()));

   class Job implements Runnable {
        private String schedule;

        public Job (String schedule) {
            this.schedule = schedule;
        }

        @Override
        public void run() {
           reportExportSchedulerTask.run(schedule);
        }
    }

Solution

  • DummyTask needs to be a Spring bean itself in order for Spring to autowire beans in it for you. You can fix this by marking it as a @Component:

    @Component
    public class DummyTask implements Runnable {
    
        @Autowired
        private FileService fileService;
    
    
        @Override
        public void run() {
            fileService.runtask(blah);
        }
    }
    

    As for the tests, you should mark it as a @SpringBootTest. This will make the beans available to the test to be autowired.

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class FileRepositoryTest {
    
        @Autowired
        private FileRepository fileRepository;
    
    
        @Test
        public void testGetCustomerDir() {
    
           //blah    
        }
    }