简体   繁体   English

在Apache Tomcat webapp中访问Spring bean的推荐方法?

[英]Recommended way to access Spring beans in Apache Tomcat webapp?

I'm developing a web application on Apache Tomcat 6 with Hibernate and Spring, I'm using different XML configuration files to define my Spring beans (like the Hibernate DAO, Quartz scheduler and some other stuff). 我正在使用Hibernate和Spring在Apache Tomcat 6上开发一个Web应用程序,正在使用不同的XML配置文件来定义我的Spring bean(例如Hibernate DAO,Quartz调度程序和其他一些东西)。 All these files are loaded at Tomcat start up via web.xml (ContextLoaderListener). 所有这些文件都是通过web.xml(ContextLoaderListener)在Tomcat启动时加载的。

Now I'm not sure what is the recommended way to get access to my beans. 现在我不确定访问我的bean的推荐方法是什么。

Should I write on class which provides the BeanFactory for all classes which should use a bean, or is it the better way to load the BeanFactory in each class. 我应该在为所有应使用Bean的类提供BeanFactory的类上写代码,还是在每个类中加载BeanFactory的更好方法。

BeanFactory bf = (BeanFactory) ContextLoader.getCurrentWebApplicationContext();

One of the core ideas of the spring framework is to minimize dependencies between classes. spring框架的核心思想之一是最小化类之间的依赖关系。 You'll get the most benefit by using this concept throughout your whole project. 通过在整个项目中使用此概念,您将获得最大的收益。 Each and every backend object should be defined as bean and can therefore use the dependency injection automatism. 每个后端对象都应定义为bean,因此可以使用依赖项注入自动机制。

If some of your Beans need to access the ApplicationContext directly (eg for requesting all Beans implementing some marker interface) you can implement the ApplicationContextAware interface, so still no factory is needed. 如果您的某些Bean需要直接访问ApplicationContext(例如,请求所有Bean实现某个标记接口),则可以实现ApplicationContextAware接口,因此仍然不需要工厂。

Use dependency injection instead. 请改用依赖项注入。 Create getters & setters in each controller class, and use your *-servlet.xml to inject the required beans via the <property> tag. 在每个控制器类中创建getter和setter,并使用您的* -servlet.xml通过<property>标记注入所需的bean。 No factory needed! 无需工厂!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM