简体   繁体   中英

Using spring to instantiate with static factory methods?

I am using spring3. I have below classes.

Transport.java

package com.net.core.ioc;

public interface Transport {
  public void getTransport();
}

Car.java

package com.net.core.ioc;

    public class Car implements Transport{
        public void getTransport(){
            System.out.println("Transport type is Car");
        }
    }

Bus.java

package com.net.core.ioc;

    public class Bus implements Transport {
        public void getTransport() {
            System.out.println("Transport type is Car");
        }

SpringService.java

package com.net.core.ioc;

    public class SpringService {
        private static SpringService service = new SpringService();

        //Static factory method
        public static SpringService createService(){
            return service;
        }

        //Instance factory methods
        public Transport createCarInstance(){
        return new Car();
        }

    public Transport createBusInstance(){
            return new Bus();
        }

    }
 }

config.xml

<context:component-scan base-package="javabeat.net.core.ioc"/>
        <bean id="springServiceStaticFactory" factory-method="createService"/>
        <bean id="springServiceCarInstance" factory-bean="springServiceStaticFactory" factory-method="createCarInstance"/>
        <bean id="springServiceBusInstance" factory-bean="springServiceStaticFactory" factory-method="createBusInstance"/>
    </beans>

Now my question is does spring manage Car and Bus instances which are being instantiated using SpringService.java class?Because i have to annotate Car and Bus classes with @Transactional annotation. Is it possible?

Spring will manage your Car and Bus instances as they are part of the ApplicationContext . What you are doing is basically the same as normally would happen with a Spring FactoryBean but you are now using your own mechanism.

However in your current setup the Car and Bus beans are singletons as they will be created once, not sure if that is what you want.

If you want to pass in values to the constructor simply modify your factory method.

public Transport createCarInstance(String name){
    return new Car(name);
}

Your bean definition should tell that it is a prototype scoped bean

    <bean id="springServiceCarInstance" factory-bean="springServiceStaticFactory" factory-method="createCarInstance" scope="prototype" />

Now in your code you can do a lookup and pass arguments to the lookup method (See javadoc ).

@Autowired
private ApplicationContext ctx;

public void myMethod() {
    Car car = ctx.getBean(Car.class, "Mercedes"); 
}

The code above should give you a fresh Car instance with the name Mercedes .

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