2

I am trying to follow this tutorial: http://www.vogella.de/articles/SpringDependencyInjection/article.html to use annotation dependency injection in my application. I set up the bean, etc like in the tutorial and then am trying to get an instance of the bean within my MainController class (a controller class that handles generating a specific page for my spring web mvc app).. I keep getting

SEVERE: Servlet.service() for servlet spring threw exception

    java.io.FileNotFoundException: class path resource [WEB-INF/applicationContext.xml] cannot be opened because it does not exist

I am doing this in my MainController:

    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    BeanFactory factory = context;
    BeanIRPlus beanirPlus = (BeanIRPlus) factory
            .getBean("BeanIRPlus");
    IRPlusInterface irPlus = beanirPlus.getIRPlus();

I have searched and searched on this and yet to find an answer that fixes my problem. My applicationContext in in webapp/WEB-INF/ and my spring app seems to be working otherwise as it was handling requests, etc before this. I have tried putting the applicationContext.xml in WEB-INF classes but still nothing. Is there any workaround to make this not search the path this way as I think its doing a relative path search. Thanks for any advice

1 Answer 1

2

Not a direct answer, but here goes.

The tutorial you have referred is for dependency injection in a standalone application and not a web application. In case of web application, spring automatically loads the context files and initializes the beans. So you would not need any of the lines specified in the MainController.

Instead, you could do something like this to use beanIRPlus bean in your controller.

@Autowired
private BeanIRPlus beanIRPlus;
Sign up to request clarification or add additional context in comments.

2 Comments

wow ok thats an eye opener :), thanks for the help, am going to try it now without that.. so how do I actually use the bean within the MainController if I need to call a method on it? Any advice / resources for this are appreciated, I have been spending hours and hours looking over things on this but sometimes miss important things like what I just did as I'm still learning.. thanks
Thank you for all your help.. I have seen the @Autowired thing before but its hard when new to spring to put 2 and 2 together sometimes as it seemed each tutorial was talking about a different way to do it (probably because some were for non-web)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.