简体   繁体   English

在spring上下文中创建bean

[英]Create bean in spring context

<bean id="configuration" class="com.mypackage.util.Configuration" factory-method="getInstance">
<property name="path" value="${path.props.app.dev}"></property>
</bean>

Then I have the following in my class 然后我在课堂上有以下内容

Configuration.getInstance();

Whereas the spring application context is loaded in another class Factory like this 而spring应用程序上下文是像这样加载到另一个类Factory中的

private Factory() {
    context = new ClassPathXmlApplicationContext("META-INF/spring.xml");
}

The problem is that before Factory class is accessed the context does not load and the configuration object gives null for path whereas when Factory is accessed and after that path property is accessed it gives the correct path. 问题是在访问Factory类之前,上下文没有加载,配置对象为路径提供null,而当访问Factory时,访问该路径属性后,它给出了正确的路径。

Please tell me how to do it correctly? 请告诉我如何正确地做到这一点? That is how can i get my member variable path with correct data without accessing Factory class. 这就是如何在不访问Factory类的情况下使用正确的数据获取我的成员变量路径。

Assuming that you are using Spring WebMVC. 假设您使用的是Spring WebMVC。 There are 2 ways: 有两种方式:

  1. Putting you bean configurations to dispatcher config XML ( mvc-dispatcher-servlet.xml ) 将bean配置mvc-dispatcher-servlet.xml调度程序配置XML( mvc-dispatcher-servlet.xml
  2. Remain your spring.xml and specify it in web.xml 保留spring.xml并在web.xml指定它

    <context-param> <param-name>contextConfigLocation</param-name> <param-value>spring.xml</param-value> </context-param>

In both cases, you will no longer need a class like Factory . 在这两种情况下,您将不再需要像Factory这样的类。 Besides, because of that Spring creates beans in singleton scope by default, you do not need to implement a getInstance() method for your com.mypackage.util.Configuration class. 此外,由于Spring默认情况下会在单例作用域中创建bean,因此您不需要为com.mypackage.util.Configuration类实现getInstance()方法。

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

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