简体   繁体   中英

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

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.

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.

Assuming that you are using Spring WebMVC. There are 2 ways:

  1. Putting you bean configurations to dispatcher config XML ( mvc-dispatcher-servlet.xml )
  2. Remain your spring.xml and specify it in 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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