Using spring @Transactional for beans created using factory method?

I am using spring3. I have classes below.

Transport.java

package com.net.core.ioc;

public interface Transport {
  public void doSave();
}

Car.java

package com.net.core.ioc;

    public class Car implements Transport{
     String name;
     public Car(String name){
         this.name=name;
      }
        public void doSave(){
            //saving logic using name
        }
    }

Bus.java

package com.net.core.ioc;

    public class Bus implements Transport {
      String id;
      public Bus(String id){
         this.id=id;
      }
        public void doSave() {
            //saving logic using id
        }

SpringService.java

package com.net.core.ioc;

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

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

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

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

    }
 }

config.xml

<context:component-scan base-package="com.net.core.ioc"/>
        <bean id="serviceLocator" class="com.net.core.ioc.ServiceLocator"factory-method="createService"/>
        <bean id="springServiceCarInstance" factory-bean="serviceLocator" factory-method="createCarInstance" scope="prototype"/>
        <bean id="springServiceBusInstance" factory-bean="serviceLocator" factory-method="createBusInstance" scope="prototype"/>
    </beans>

Now I get beans, as shown below:

Transport request = (Transport)applicationContext.getBean("springServiceCarInstance","someName");
request.doSave();

Now can I use spring transactions here? I mean, can I comment on car and bus classes using @Transactional?

+4
source share
3 answers

No. Since the car and the bus were not created by spring factory, the instances you get will not be woven using proxies, so annotations will be pointless.

spring, initializeBean createBean. java doc AutoWireCapableBeanFactory.

Can Bus spring beans, getBean ( "beanName", BeanType.class), spring .

@Component
@Scope("singleton")
public class CarFactory {

    @Autowired
    private AutowireCapableBeanFactory autowireCapableBeanFactory;

    public Car create( Make make, Model model, Year year ) {
        Car car = new Car( make, model, year );

        // this will apply the post processors including ones that might wrap the original bean
        // such as transaction interceptors etc.
        Car carProxy = Car.class.cast(autowireCapableBeanFactory.configureBean(car, "carBean"));
        return carProxy;
    }
}
+2

Car Bus . . / bean, , bean.

doSave, beans.

@Component
public class CarRepository{

    @Transactional
    public void doSave(Car car){

    }
}
+2

CarFactory Junit? AutowireCapableBeanFactory Junit

0

All Articles