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!
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.
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.
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 .
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With