Load Image into Application Context Spring from database. I use mybatis api

326 views Asked by At

I use spring-mvc mybatis 3.2.8. I want to read some image from database and store in on ApplicationContext. I have a dao class to read image

dao class

public Interface DaoImage {
   public List<byte[]> selectImage();
}

InitializationService.java

public interface InitializationiService {
public List<byte[]> loadImage();
}

InitializationServiceImpl.java

public class InitializationImpl implements InitializationService{
@Autowoired
private DaoImage img;

@Overrides 
public List<byte[]> loadImage(){
   return img.selectImage();
}

}

InitializeApplication.java

public class InitializationApplication extends ContextLoaderListener{
@Autowired
private InitializationService service;
    @Override
    public void contextInitialized(ServletContextEvent event) {

        List<byte[]> list = service.loadImage();        
        event.getServletContext().setAttribute("contextImage", list);


    }

}

When the application start the List list = service.loadImage(); is null.

Can anyone help ?

2

There are 2 answers

0
chetra tep On

I have found the solutioin now :

public class InitializationApplication extends ContextLoaderListener implements ServletContextAware{
@Autowired
private InitializationService service;
    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext ctx = event.getServletContext();
        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(ctx);
        InitializationService  service = (InitializationService)springContext.getBean("InitializationService");
        List<byte[]> list = service.loadImage();        
        event.getServletContext().setAttribute("contextImage", list);

    }

@Override
public void setServletContext(ServletContext servletContext) {
    this.servletContext = servletContext;
}

}
0
coderz On

Seems you miss annotation definition in InitializationServiceImpl.java.

Try:

@Component("initializationService")
public class InitializationImpl implements InitializationService {
...
}

In InitializeApplication.java

@Autowired
@Qualifier("initializationService")
private InitializationService service;