自动装配不能在类@Entity中工作

自动装配不能在类@Entity中工作,第1张

自动装配不能在类@Entity中工作

您可以采用两种方法:

  1. 尝试从
    @Entity
    类的方法中获取Spring管理的Bean的实例
  2. 按照@Stijn Geukens的建议更改设计,并使您的实体成为POJO,而没有任何逻辑或依赖项注入机制

如果通过选项1,则必须显式访问Spring的上下文并检索所需的bean实例:

@Componentpublic class Spring implements ApplicationContextAware {    private static final String ERR_MSG = "Spring utility class not initialized";    private static ApplicationContext context;    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        context = applicationContext;       }    public static <T> T bean(Class<T> clazz) {        if (context == null) { throw new IllegalStateException(ERR_MSG);        }        return context.getBean(clazz);    }    public static <T> T bean(String name) {        if (context == null) { throw new IllegalStateException(ERR_MSG);        }        return (T) context.getBean(name);    }}

您需要让Spring扫描此类以使其工作。

然后,在您的内

@EntityClass
,执行以下 *** 作:

public void setCurrentLanguage(){    GestoreMessaggi gestoreMessaggi = Spring.bean(GestoreMessaggi.class);    gestoreMessaggi.gest();        }

仅此而已。请注意,你不会需要自动装配

GestoreMessaggi
成你的
@Entity
了。还请注意,
Spring和大多数社区都不推荐这种方法 ,因为它将域类(您的
@Entity
类)耦合到Spring类。

如果您选择选项2,那么您所需要做的就是让Spring像往常一样解决自动装配问题,但要 在您的实体之外
(即在dao或服务中),并且如果您的实体需要您用一些消息或其他内容来填充它,只需对其调用一个setter。(然后,由您决定是否设置

@Entity
s属性
@Transient
,具体取决于您的要求)。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5094336.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存