Spring将组件作为参数传递到方法中

Spring将组件作为参数传递到方法中,spring,Spring,我有一个springbean,它是一个服务工厂。大概是这样的: public abstract class Serivce { public abstract Type getType(); } @Autowired public ServiceFactory factory; public void methodA(Type type) { Service service = factory.getFor(type); service.baseMethod();

我有一个spring
bean
,它是一个服务工厂。大概是这样的:

public abstract class Serivce {
     public abstract Type getType();
}
@Autowired
public ServiceFactory  factory;

public void methodA(Type type) {
    Service service = factory.getFor(type);
    service.baseMethod();

    methodB(type);
}

public void methodB(Type type) {
    Service service = factory.getFor(type);
    serivce.otherBaseMethod();
}
具体实施:

@Service
public class CarService extends Service {}

@Service
public class BicycleService extends Service {}
工厂bean:

@Component
public class ServiceFactory {
     private final Map<Type, Service> typeToService = new HashMap<>();

    //Autowire'ing services here
    //get concrete service method here
}
如您所见,我必须第二次调用
methodB
中的
factory
bean。我是否可以将
服务
实例传递给
methodB()
而不是
类型
?避免第二次呼叫工厂?安全吗?

如果
otherBaseMethod()
是无状态的(不在
服务
实例中设置/维护状态),则可以将bean实例作为
methodB()
方法的参数传递,而不存在任何线程安全问题,例如:

public void methodA(Type type) {
    Service service = factory.getFor(type);
    service.baseMethod();    
    methodB(service);
}

private void methodB(Service service) {
    service.otherBaseMethod();
}
作为旁注,我将
methodB()
的修饰符更改为private,因为bean参数应该只由类成员提供,以与您的用例保持一致

交错调用
otherBaseMethod()
在它们之间确实没有副作用。
这不是Spring特有的。这是Java特有的。因为在Spring中,我们被鼓励尽可能多地定义Spring服务(一旦bean创建),这意味着通常的交叉调用通常不是问题