SJS
SJS

Reputation: 5667

Better way to access beanFactory in Spring3 Web App

I am trying to find a better way to access beanFactory in Spring3 Web App. Right now I setup a config.xml file with all my services that my system is going to use and in the controller I ad a line of code like:

private static XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("config.xml"));

in each controller.. Does anyone know of any better way to do this?

Upvotes: 1

Views: 1094

Answers (1)

GriffeyDog
GriffeyDog

Reputation: 8376

If you're using Spring MVC, presumably you've defined a servlet in web.xml to handle the requests, like:

  <servlet>
    <description></description>
    <display-name>dispatcher</display-name>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>

In which case you should have a Spring config file named something like dispatcher-servlet.xml in your web-inf directory. Put your bean definitions in there and they will get defined and be available when the servlet starts up.

EDIT:

Importing one bean configuation file into another, from section 3.2.2.1 of the Spring reference:

<beans>

    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>

</beans>

Autowiring bean example in controller:

@Controller
public class MyController {
  @Autowired
  private MyBeanClass myBeanName;
  ...
}

Upvotes: 4

Related Questions