Spring newbie here.
I've read comments that it's not a good idea to use ApplicationContext.getBean() to retrieve beans, because that violates Inversion of Control. Instead, you should just declaratively "inject" your bean where you need it.
So how do I do it?
Let's say I have my Spring MVC Controller class, and I want to inject my bean here:
And the bean that I want to inject is a DAO bean, defined in my applicationContext.xml as follows (I'm using Hibernate to connect to the DB):Code:public class HelloController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) { // use my DAO bean here } }
So my MainDao bean is defined and created by Spring, and now I need to inject it into my Controller class above, that handles the page. How do I do it? Is it enough to just create a member MainDao variable in my Controller, and assume it will be populated? Thanks.Code:<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mappingResources"> <list> <value>Movie.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> <prop key="show_sql">true</prop> </props> </property> </bean> <bean id="MainDao" class="MyApp.dao.MainDao"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean>


Reply With Quote
