1

In my current project, when this method is called:

public Collection<? extends Object> list_values() throws Exception {
    String nome = classe().getSimpleName();
    String nome_service = nome+"Service";
    String local_service = "com.spring.model."+nome;
    Class<?> clazz = Class.forName(local_service.toLowerCase()+"."+nome_service);
    Object serv = clazz.newInstance();
    Collection<? extends Object> list = (Collection<? extends Object>) serv.getClass().getMethod("lista").invoke(serv);
    return list;
}

the application triggers a InvocationTargetException caused by this error:

Caused by: java.lang.NullPointerException
    at com.spring.config.generic.service.basicService.lista(basicService.java:51)

where basicService is the superclass for the class stored in the variable clazz.

Anyone can tell me what I am doing wrong here? What the right way to make a new instance of this class?

ps.: the line 51 in basicService is placed inside this method:

@Transactional
public List<?> lista() {
    return dao.findAll();
}

and the member dao is defined this way:

@Autowired
protected Dao<E> dao;
Kleber Mota
  • 8,521
  • 31
  • 94
  • 188
  • Well when is this method list_values called? And who instantiates the bean which holds DAO is it by Spring? Also have you implemented/extended any Spring bean lifecycle interface/class? – SMA Nov 02 '14 at 13:37
  • @almasshaikh this method is called inside the class for the custom tag Select, in the method `doStartTag(...)`. – Kleber Mota Nov 02 '14 at 14:13

1 Answers1

0

Ok, I solve this problem adding to my project a class named ApplicationContextHolder, with this code:

@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

}

the final code for the function list_values(...) is that:

public List<?> list_values() throws Exception {
    String nome = classe().getSimpleName();
    Class<?> clazz = Class.forName("com.spring.model."+nome.toLowerCase()+"."+nome+"Service");
    Object object = clazz.newInstance();
    ApplicationContextHolder.getContext().getAutowireCapableBeanFactory().autowireBean(object);
    return (List<?>) object.getClass().getMethod("lista").invoke(object);
}
Kleber Mota
  • 8,521
  • 31
  • 94
  • 188