Spring将组件作为参数传递到方法中
我有一个springSpring将组件作为参数传递到方法中,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();
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创建),这意味着通常的交叉调用通常不是问题