栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自动装配不能在类@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
,具体取决于您的要求)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428680.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号