1

I was wondering if there's a way to Load Springs application context without having to define it in a web.xml.

I see you can use:

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

But if you wanted to use a bean you've got to getBean() to have access to it. I am thinking possibly there could be a way to load the context programmatically as would the definition in web xml, without having to call getBean.

Any ideas?

2 Answers 2

1

You can use:

ctx.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                  AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);        

...where ctx is your ClassPathXmlApplicationContext to avoid the need to ever call getBean() - any spring bean fields on this will be autowired for you.

Sign up to request clarification or add additional context in comments.

Comments

0

There is a way. You just have to read official documentation. The relevant part is here.

Edit: Sorry, misread your question. You can use

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

and load it using ServletContextListener at application startup. When your application starts, if you've configured your bean wiring properly, you shouldn't have to call getBean() to access all of your beans. Treat it like you're using Java SE.

5 Comments

I don't see anything in that part that works without having to define it in a web.xml
You mean all i need is the ClassPathXmlApplicationContext instantiation in a ServletContextListener and it will do the the rest for me?
@Bitmap: almost. You'll still need to use getBean() for "top-level" beans that are in your wiring hierarchy. The rule is: if you use the "new" keyword for creation of beans, they won't be wired using Spring. If you make a static public getter for app. context in ServletContextListener, you can get your beans pretty effortlessly when you need to do.
Could've done it neatly the way the web.xml does it - I am experimenting that instead. Reason been I never want to call getBean.
@Bitmap: I don't think it's possible; you'll probably need to call getBean at least once.

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.