避免Spring Application Context实例化

时间:2013-08-12 13:42:37

标签: java spring spring-mvc

我使用Spring 3进行简单的配置。

我有一个名为PropertyBeans.xml的XML文件:

<bean id="propertyBean" class="com.myapp.PropertyBean">
    <property name="rootDirLogPath" value="C:\Users\dede" />
</bean>

我有与此XML匹配的bean,然后我想将此bean与注入的值一起使用。其实我有:

ApplicationContext context = new ClassPathXmlApplicationContext("AppPropertyBeans.xml");
PropertyBean obj = (PropertyBean) context.getBean("propertyBean");
String rootDirLogPath = obj.getRootDirLogPath();

这很好但我想知道是否有办法在每次我想使用bean时避免ApplicationContext的实例化。我听说BeanFactory是个好主意吗?其他解决方案是哪些?

换句话说:我是否应该在Spring MVC中的每个Controller中调用此Application上下文实例?

4 个答案:

答案 0 :(得分:4)

如果要在控制器中使用spring bean,请在applicationContext.xml中添加一行:

<context:spring-configured/>
<task:annotation-driven/>
<context:component-scan base-package="by" />

然后按照以下方式编写控制器:

@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;

        // methods with @RequestMapping annotation
}

这是微不足道的事情,所以如果您有疑问,强烈建议您阅读&#34; Spring in action book&#34;,第7章:构建Web应用程序

答案 1 :(得分:0)

ApplicationContext的整个想法是有一个(因此名称,应用程序的上下文)。

所以,如果你每次创建一个新的,那你就错了。

如果正确使用依赖注入,则包含该代码的对象将已由注入容器(Spring)实例化,并且将注入propertyBean。

答案 2 :(得分:0)

您可以简单地将上下文添加为类中的成员,如:

private ApplicationContext context;

并在构造函数或init()方法中实现它。

答案 3 :(得分:0)

使用autowiring或实现InitializingBean界面。