Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring boot @Autowired repository is null

Hi I am importing data into the database from the csv file and I’m using opencsv to do it.
I have a separate class that I want to do the job unfortunately the repositories are null when I add them with @ Autowired.
The class:

@Service
public class CsvPriceParser {

    @Autowired
    PriceRepository priceRepository;

    @Autowired
    ProductRepository productRepository;

    public void parse(InputStream is) throws IOException {
        try (Reader reader = new InputStreamReader(is, "UTF-8");) {
            CsvToBean<CsvPrice> csvToBean = new CsvToBeanBuilder(reader).withType(CsvPrice.class).withIgnoreLeadingWhiteSpace(true).withSeparator('\t').build();
            Iterator<CsvPrice> csvPriceIterator = csvToBean.iterator();

            final List<PriceEntity> entitiesToSave = new ArrayList<>();

            for (final CsvPrice price : csvToBean) {

                ProductEntity productEntity = null;
                try {
                    productEntity = productRepository.findOneByProductName(price.getProductName());
                } catch (NullPointerException e) {
                    productEntity = new ProductEntity(price.getProductName());
                    productRepository.save(productEntity);
                }
                final PriceEntity priceEntity = new PriceEntity();
                priceEntity.setProduct(productEntity);
                priceEntity.setMaterialPrice(price.getMaterialPrice());
                priceEntity.setLabourExpenses(price.getLabourExpenses());
                priceEntity.setOtherExpenses(price.getOtherExpenses());
                priceEntity.setDateFrom((Date) price.getDateFrom());
                entitiesToSave.add(priceEntity);
            }

            System.out.println(entitiesToSave.toString());

            if (!entitiesToSave.isEmpty()) {
                priceRepository.saveAll(entitiesToSave);
            }

        }
    }
}

This is the repository:

@Repository
public interface PriceRepository extends JpaRepository<PriceEntity, Long> {
    PriceEntity findById(long id);

    List<PriceEntity> findAll();
}

This is the entity:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class PriceEntity {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="price_id")
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", nullable = false)
    private ProductEntity product;

    @Column(name="material_price")
    private BigDecimal materialPrice;

    @Column(name="labour_expenses")
    private BigDecimal labourExpenses;

    @Column(name="other_expenses")
    private BigDecimal otherExpenses;

    @Column(name="date")
    private Date dateFrom;

//constructors, getters and setters
}

Unfortunately, both jpa repositories are null in this class even though I am using @Service annotation. What am I doing wrong?

UPDATE rest controller uses CsvPriceParser.

@RestController
@RequestMapping("/api")
public class PricesRest implements PricesApi {

    @Autowired
    private PriceRepository priceRepository;

    @Autowired
    private ProductRepository productRepository;

@Override
    public ResponseEntity<Void> uploadPricesCsv() {
        FileStream fileStream = new FileStream();
        InputStream isf = fileStream.getFileFromResourceAsStream("price_list.csv");
        //(InputStream is = file.getInputStream())
        try {
            CsvPriceParser csvPriceParser = new CsvPriceParser();
            csvPriceParser.parse(isf);
            return ResponseEntity.ok().build();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }
}

The package structure:

enter image description here

>Solution :

You shouldn’t create the CsvPriceParser bean yourself. You should also autowire it. Otherwise spring doesn’t know about it and there’s nothing injected.

There’s no need to autowire the repositories in your controller, as you aren’t using them directly. Only autowire CsvPriceParser.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading