Results 1 to 2 of 2

Thread: Factory

  1. #1

    Default Factory

    I want to use spring to implement a factory that takes a parameter in the factory method call. The value of that parameter is dynamically determined at runtime and is not known beforehand. Here is a sample config:
    HTML Code:
        <bean id="a" class="com.sepaton.sms.s2xmgr.test.A"/>
    
        <bean id="testValue" class="java.lang.String" factory-bean="a"
              factory-method="getMappedValue">
            <constructor-arg name="key" value=""/>
        </bean>
    The class A looks like this:
    Code:
    public class A {
        private Map<String, String> testMap = new HashMap<String, String>();
    
        public A() {
            testMap.put("1", "Value 1");
            testMap.put("2", "Value 2");
            testMap.put("3", "Value 3");
            testMap.put("4", "Value 4");
        }
    
        public String getMappedValue(String key) {
            return testMap.get(key);
        }
    }
    And my test class looks like this:
    Code:
    public class SampleSpringTest {
        public static void main(String[] args) {
            ApplicationContext springContext = new ClassPathXmlApplicationContext("spring/test/sample-spring-config.xml");
            String testValue = (String) springContext.getBean("testValue", "2");
            System.out.println(testValue);
        }
    }
    So my spring config is supplying a blank for the key value, and of course that returns null. Is there a way I can have spring directly return the keyed value in the getBean method without having to get the factory bean (A in this example) in a separate step?

  2. #2

    Default

    Every time I ask a question I find my own answer it seems. The solution is to set the scope of my factory bean to prototype.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •