Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access applicationContext from a Controller

Tags:

spring-mvc

I'm using a Spring MVC Project from Netbeans and I've moved the applicationContext.xml file to /src/conf because I've read WEB-INF isn't the correct folder. I can't access to the application context from a controller in /src/java/web/controller. I've tried several ways and it doesn't deploy the project.

I would like a link to learn more about paths in a web project, pleas.

I think this could help us to figure out:

public class TasksController implements Controller {
private TaskManager taskManager;
protected final Log logger = LogFactory.getLog(getClass());

public TaskController() {
    ApplicationContext context = new FileSystemXmlApplicationContext("/WEB-INF/applicationContext.xml");    
    taskManager = (TaskManager)context.getBean("taskManager");
}

@Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException {

    logger.info("Returning view from TaskController");

    Map<String,Object> tasks = new HashMap<String,Object>();

// Get tasks from model

    return new ModelAndView("tasks","tasks",tasks);
}

Bye!

like image 414
Jonás Avatar asked Jan 08 '12 18:01

Jonás


People also ask

How do I access application context?

To get a reference to the ApplicationContext in a Spring application, it can easily be achieved by implementing the ApplicationContextAware interface. Spring will automatically detect this interface and inject a reference to the ApplicationContext: view rawMyBeanImpl. java hosted by GitHub.

Can we use ApplicationContext in Spring boot?

ApplicationContext is a corner stone of a Spring Boot application. It represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.

Where is Spring application context file?

The basis for the context package is the ApplicationContext interface, located in the org. springframework. context package. Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory .


1 Answers

Ouch. OK, you don't instantiate new contexts from within your controller. The context has already been configured by Spring, you just have to ask Spring for it.

Make your controller implement BeanFactoryAware, and Spring will then inject the context for you by automatically calling setBeanFactory:

public class TasksController implements Controller, BeanFactoryAware {
  private TaskManager taskManager;

  public void setBeanFactory(BeanFactory context) {
     taskManager = (TaskManager)context.getBean("taskManager");
  }

  // handleRequest as before
}
like image 101
skaffman Avatar answered Nov 29 '22 05:11

skaffman