Obtaining spring application context

Spring is  a container where it manages the beans (objects) for injecting(DI) them to another objects which is also again  managed by spring. However, in some cases you need to provide managed objects to another piece of code that is not managed by spring. Lets say, we have an pure servlet application where it serves some formatted data and needs repository data access through spring-data-jpa (i will write some notes about it). Since your code is not managed by spring (of course by spring-web-mvc you can make your code run un the container) you need those managed object and how to do it?







/*For The Love Of Delphi, use Custom prefix as abstract or base*/
public class MyCustomObject { 
 //Its a private member to access repository. 
 //Spring needs to wire MyTestRepository instance to it.
@Autowired 
private MyTestRepository testRepository;

@Override protected void init(HttpServletRequest request) { 
 ServletContext servletContext = request.getSession( ).getServletContext( );
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
AutowireCapableBeanFactory factory = webApplicationContext.getAutowireCapableBeanFactory();
factory.autowireBean(this); 
 //We wants factory to scan this object and autowire members.
}

Whenever init() method is called, this code piece will access spring and obtain thecurrent WebApplicationContext. Usually, we can directly lookup bean definitions and fetch
MyTestRepository bean manually however in this sample, we marked members as autowired andallowed application context to scan and autowire members automatically.

Comments

Popular posts from this blog

Fedora 27 how to install broadcom wifi driver