Instantiate an object from a Spring-managed class

Asked

Viewed 371 times

1

Does anyone know how to instantiate an object from a Spring-managed class (e.g., a Jparepository class) in a class not managed by Spring?

1 answer

1


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

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

or if you are on an Httpservlet:

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

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

SuaClasse instancia = context.getBean(SuaClasse.class);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.