我使用Spring 3做了一个简单的配置。
我有一个名为 PropertyBeans.xml 的 XML 文件:
<bean id="propertyBean" class="com.myapp.PropertyBean">
<property name="rootDirLogPath" value="C:\Users\dede" />
</bean>
我有一个匹配这个 XML 的 bean,然后我想使用这个 bean 和注入(inject)的值。其实我有:
ApplicationContext context = new ClassPathXmlApplicationContext("AppPropertyBeans.xml");
PropertyBean obj = (PropertyBean) context.getBean("propertyBean");
String rootDirLogPath = obj.getRootDirLogPath();
这很好用,但我想知道是否有一种方法可以避免每次我想使用 bean 时都实例化 ApplicationContext。我听说过 BeanFactory 是个好主意吗?还有哪些解决方案?
换句话说:我是否应该在 spring MVC 中的每个 Controller 中调用这个应用程序上下文实例化?
最佳答案
如果你想在 Controller 中使用 spring bean,在 applicationContext.xml 中添加一行:
<context:spring-configured/>
<task:annotation-driven/>
<context:component-scan base-package="by" />
然后按照以下方式编写您的 Controller :
@Controller
public class IndexController {
@Autowired
private UserService userService;
@Autowired
private GroupService groupService;
// methods with @RequestMapping annotation
}
这是微不足道的事情,所以如果您有任何疑问,强烈建议阅读“Spring in action book”,第 7 章:构建 Web 应用程序
关于java - 避免 Spring ApplicationContext 实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18188562/