gpt4 book ai didi

java - 从组件 bean 获取原型(prototype) bean 的正确设计模式是什么?

转载 作者:行者123 更新时间:2023-11-30 11:00:59 24 4
gpt4 key购买 nike

我只是想知道好的架构设计是什么样的。

  • 假设我们有一个CarRepository,它管理汽车租赁应用程序中所有Car 类型的bean。
  • Car bean 是原型(prototype)类型
  • CarRepository bean 是 repository 类型(单例)
  • 现在,要求 CarRepository 创建一个新的 Car bean,例如当租赁公司购买新车时。

当然,我可以实现 ApplicatioContextAware 并使用 context.getBean("car"),但对我来说,它不太符合依赖的想法注入(inject)。将生命周期较短的 bean 注入(inject)单例的最佳做法是什么?

更新:也许我应该添加一个示例以使其更清楚。

@Repository
public class CarRepository {
private List<Car> cars;

public void registerNewCar(int id, String model) {
// I don't want to access the Spring context via ApplicationContextAware here

// Car tmp = (Car) context.getBean("car");
// car.setId(id);
// car.setModel(model);
// cars.add(tmp);
}
}

@Scope("prototype")
public class Car {
private int id;
private String model;

// getter and setters
}

最佳答案

Spring 提供了一种机制,可以处理将较短生命周期的 bean 注入(inject)到较长生命周期的 bean 中。它称为作用域代理。它的工作原理是为单例注入(inject)一个代理,该代理将通过搜索 bean 实例的较短范围(如 session 或请求)并委托(delegate)给该实例来处理方法调用。

如果您使用 xml 或注释来配置您的应用程序或您使用的 Spring 版本,您没有指定。您可以在 reference guide 中阅读有关使用 xml 配置作用域代理的更多信息。 .我将举例说明如何在 Spring 4-ish 环境中使用注释配置它。

对我来说最好的方法是使用元注释机制。它允许您创建自己的注解,稍后 Spring 将使用这些注解来配置您的应用程序。例如:

@Retention(RUNTIME)
@Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode=ScopedProxyMode.TARGET_CLASS)
public @interface SessionScoped{
}

当在 @Component(或@Service 或任何其他特化)类或 Java 配置中的 @Bean 方法上指定时,这样的注释将导致该 bean 作为代理注入(inject)。例如:

@Configuration
@EnableAspectJAutoProxy
public class MyConfig{

@SessionScoped
@Bean
public MyClass myBean(){
// return your bean
}
}

综上所述,您的示例确实让我觉得您应该使用实体 (Car) 和存储库。参见 Spring Data如果您正在设计模型层并且希望将 Cars 数据存储在数据库等中。

关于java - 从组件 bean 获取原型(prototype) bean 的正确设计模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31368327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com