-1

I have a DaoImpl of a repository that i want to autowire . The class is like this

@Repository("referralDao")
@Transactional(value = "txManager", propagation = Propagation.REQUIRES_NEW , readOnly = true)
public class ReferralDaoImpl extends ReferralCommonDao  implements IReferralDao {
    @Override
    public ReferralProperty getReferralProperty(String name) {
        String sQuery = " FROM " + ReferralProperty.class.getSimpleName() + " WHERE name = :name";
        Query query = getCurrentSession().createQuery(sQuery);
        query.setParameter("name", name);
        ReferralProperty property = (ReferralProperty)query.uniqueResult();
        return property;
    }
}

I further have a controller where I am autowiring this class. The controller:

@Controller
@RequestMapping(value="UploadExcel")
public class ExcelController {
       private boolean isMultipart;
   private String filePath;
   private String fileName;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;
  @Autowired
  private ReferralDaoImpl referralDaoImpl;

  private ReferralProperty referralProperty;

@RequestMapping(value="/excel", method=RequestMethod.GET )
public String excel() {
    return "UploadExcel/excel";
}
@RequestMapping(value="UploadNew" , method=RequestMethod.POST)
public String excel1() {
    return "UploadExcel/excel";
}
@RequestMapping(value = "Upload", method = RequestMethod.POST)
public String doPost (HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException , Exception{  
          isMultipart = ServletFileUpload.isMultipartContent(request);
          response.setContentType("text/html");
          referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.directory");
          filePath = referralProperty.getValue();
      //    java.io.PrintWriter out = response.getWriter( );
          if( !isMultipart ){
             return "index";
          }
          DiskFileItemFactory factory = new DiskFileItemFactory();     
          factory.setSizeThreshold(maxMemSize);     
          factory.setRepository(new File("/home/aman"));
          ServletFileUpload upload = new ServletFileUpload(factory);         
          upload.setSizeMax( maxFileSize );
          try{ 
          List fileItems = upload.parseRequest(request);
          Iterator i = fileItems.iterator();           
          while ( i.hasNext () ) 
          {
             FileItem fi = (FileItem)i.next();
             if ( !fi.isFormField () )  
             {

                String name = fi.getName();
                System.out.println(name +  "\n\n\n\n\n\n\n");
                referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.name");
                /*referralProperty.setValue(name);
                referralProperty.setDescription(name);
                referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.name");
                System.out.println(referralProperty.getDescription() +  "\n\n\n\n\n\n\n");*/
                fileName = referralProperty.getValue();
                if( fileName.lastIndexOf("\\") >= 0 ){
                   file = new File( filePath + 
                   fileName.substring( fileName.lastIndexOf("\\"))) ;
                }else{
                   file = new File( filePath + 
                   fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                }
                fi.write( file ); 
                processExcel p = new processExcel();
                int p1 = p.Excel();
           //     Excel();
             }
          }    
       }catch(Exception ex) {
           System.out.println(ex);
       }
          return "UploadExcel/downloadexcel";
      }  
@RequestMapping(value = "Download", method = RequestMethod.POST)
public void doPost1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.directory");
    String filepath = referralProperty.getValue();
    referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.name");
    String filename = referralProperty.getValue();
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    FileInputStream fileInputStream = new FileInputStream(filepath + filename);
    int i;
    while ((i = fileInputStream.read()) != -1) {
        out.write(i);
    }
    fileInputStream.close();
    out.close();
}
public int Excel() throws Exception
{
    System.out.println(referralDaoImpl.toString());
    System.out.println(referralProperty.toString());
    try {
        boolean eligible;
        referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.directory");
        String filepath = referralProperty.getValue();
        referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.name");
        String filename = referralProperty.getValue();
        FileInputStream myInput = new FileInputStream(filepath+filename);
         XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);
         XSSFSheet mySheet = myWorkBook.getSheetAt(0);
         XSSFRow row = mySheet.getRow(0);
         int emailColumn = 0;
         int eligibilityColumn = row.getLastCellNum();
         for(Cell cell : row) {
             XSSFCell cell1 = (XSSFCell)cell;
             if(cell1.getStringCellValue().equals("email") || cell1.getStringCellValue().equals("Email")) 
             {
                 emailColumn = cell1.getColumnIndex();
                 break;
             }

         }
         XSSFCell cell2 = (XSSFCell)row.createCell(eligibilityColumn);
         cell2.setCellValue("Eligibility");
         for (Row row1 : mySheet)
         {       
             XSSFCell cell1 = (XSSFCell)row1.getCell(emailColumn);
             if(row1.getRowNum()!=0 && cell1!=null) {
             eligible = isValidRefree(cell1.getStringCellValue());
             if(eligible==true)
             {
                 cell2 = (XSSFCell)row1.createCell(eligibilityColumn);
                 cell2.setCellValue("Eligible");
             }
             else
             {
                 cell2 = (XSSFCell)row1.createCell(eligibilityColumn);
                 cell2.setCellValue("InEligible");           
             } 
         }
         }
         myInput.close();
         FileOutputStream output_file =new FileOutputStream(new File(filepath+filename));     
         System.out.println(filepath+filename);
         myWorkBook.write(output_file);       
         output_file.close();     

    } catch (Exception e) {
        System.out.println(e.toString());
    }   
    return 1;
}

public boolean isValidRefree( String email)
{
    return true;
}

}

Here the class gets autowired without any problem and everything works fine. Now if I make another package and a class in it called processExcel.java the class looks like this:

@Service
public class processExcel {

@Autowired
private ReferralDaoImpl referralDaoImpl;

private ReferralProperty referralProperty;

public int Excel() throws Exception
{

    //System.out.println(referralDaoImpl.toString());
    System.out.println(referralProperty.toString());
    try {
        boolean eligible;
        System.out.println("akjsfbjaksf" + "\n\n\n\n\n");
        referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.directory");
        System.out.println("akjsfbjaksf" + "\n\n\n\n\n");
        String filepath = referralProperty.getValue();
        System.out.println("akjsfbjaksf" + "\n\n\n\n\n");
        referralProperty = referralDaoImpl.getReferralProperty("excel.sheet.name");
        String filename = referralProperty.getValue();
        System.out.println("akjsfbjaksf" + "\n\n\n\n\n");
        FileInputStream myInput = new FileInputStream(filepath+filename);
         XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);
         XSSFSheet mySheet = myWorkBook.getSheetAt(0);
         Iterator<Row> rowIter = mySheet.rowIterator();
         while(rowIter.hasNext()){
             System.out.println("akjsfbjaksf" + "\n\n\n\n\n");
             XSSFRow myRow = (XSSFRow) rowIter.next();
             Iterator<Cell> cellIter = myRow.cellIterator();
             if(cellIter.hasNext()) {
                 XSSFCell cell = (XSSFCell)cellIter.next();
                 String email = cell.getStringCellValue();
                 eligible = isValidRefree (email);
                 if(eligible == true)
                 {
                     if (cellIter.hasNext()){    
                         XSSFCell cell1 = (XSSFCell) cellIter.next();
                         cell1.setCellValue("Eligible");
                     }
                     else
                     {
                         XSSFCell cell1 = myRow.createCell(1);
                         cell1.setCellValue("Eligible");
                     }

                 }
                 else
                 {
                     if(cellIter.hasNext()){
                         XSSFCell cell1 = (XSSFCell) cellIter.next();
                         cell1.setCellValue("InEligible");
                     }
                     else
                     {
                         XSSFCell cell1 = myRow.getCell(1);
                         cell1.setCellValue("InEligible");
                     }

                 }                       
             }   
         }
         myInput.close();
         FileOutputStream output_file =new FileOutputStream(new File(filepath+"ama.xlsx"));     
         System.out.println(filepath+filename);
         myWorkBook.write(output_file);       
         output_file.close();    

    } catch (Exception e) {
        System.out.println(e.toString());
    }

    return 1;
}

public boolean isValidRefree( String email)
{
        return true;
    }
}

and try to autowire ReferralDaoImpl it doesn't work and shows NUllPointerException. Why is this happening?

kryger
  • 12,906
  • 8
  • 44
  • 65
Evan Root
  • 279
  • 1
  • 5
  • 19

2 Answers2

1

Checking your code I see that you instantiate your processExcel manually in ExcelController here processExcel p = new processExcel(); and that is your problem.

For Spring to be able to autowire anything you need to use the bean created by Spring and when you use new to do so, Spring doesn't know anything about this object.

The correct way to use it is autowiring that class as well, and using this bean instead of creating your own:

@Autowired
private processExcel processExcel;

Just a quick heads up, don't use lowercases for classes names and always autowire the interfaces, not the implementations.

dambros
  • 4,252
  • 1
  • 23
  • 39
-1

Make sure spring context is initialised and loaded before this class loads.