使用@Configurable 域对象属性根据数据分配特定行为

Using @Configurable domain object properties to assign a specific behaviour based on data

我有一个如下所示的域对象。 我需要使用从数据库中获取的数据(本例中为"type")来获取并注入正确的服务类型。

我得到这个输出,这意味着在调用期间未设置数据库数据:

entity is a bean postconstruct: PocProduct [id=null, type=null, productName=null].. attching behavior!

当我尝试使用初始化 Bean 时,我得到了同样的结果。 正确的配置方法是什么?

@Entity
@Table(name = "AAA_POC_PROD")
@Configurable(dependencyCheck = true)
@Scope("prototype")
public class PocProduct implements Serializable, InitializingBean {
    /**
     *
     */
    private static final long serialVersionUID = 1136936011238094989L;

    @Id
    private String id;
    private String type;
    private String productName;

    @Transient
    private Behaviour behaviour;

    @Transient
    @Autowired
    private BehaviourFactory behaviourFactory;
    //getters and setters

    @PostConstruct
    public void attachBehavior() {
        System.out.println("entity is a bean postconstruct: " + this + ".. attching behavior!");
        //Need to call this : depends on type which is fetched from DB
       // this.behaviour = behaviourFactory.getTypeBasedBehaviour(type);
    }


}

Configurable bean 由 Spring 在构造之后或之前初始化,具体取决于 @Configurable.preConstruction 属性的值。从数据库加载实体时,这意味着以下事件序列:

  1. JPA 提供程序通过反射调用它的构造函数来创建实体
  2. 构造函数执行时,spring-aspects' AnnotationBeanConfigurerAspect拦截构造函数执行,并且在构造函数执行之前(或之后),Spring将通过执行任何配置这个新创建的对象您在 spring 上下文中的 bean 配置,包括属性的自动装配。
  3. JPA 提供程序将接收已由 Spring 配置的此对象,并将开始使用从数据库中获取的数据填充其持久属性。
  4. 可选地,如果您设置了 @PostLoad 方法,JPA 提供程序将调用这些方法,以便您的实体有机会在实体被数据库中的数据完全填充后继续工作。

根据我所看到的你正在尝试做的事情,这第四步是你应该放置自定义行为逻辑的地方,假设其他一切都正常工作。