Instantiate an object of a class managed by Spring

1

Does anyone know how to instantiate an object from a Spring-managed class (eg: a JPARepository class) in a class not managed by Spring?

    
asked by anonymous 21.12.2016 / 22:05

1 answer

1

You need to access the ApplicationContext of Spring in some way. As you said that this class is not managed by the same, I think you will have to instantiate it:

ApplicationContext context = new ClassPathXmlApplicationContext("resources/spring.xml");

or if you are in a HttpServlet:

WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

It will depend on the context of your application. Once you have context , getting an instance is simple:

SuaClasse instancia = context.getBean(SuaClasse.class);
    
22.12.2016 / 11:21