Load application context without using web.xml
I was wondering i开发者_运维技巧f 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?
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.
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.
精彩评论