首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Autowired为null

@Autowired为null
EN

Stack Overflow用户
提问于 2013-08-23 21:02:59
回答 3查看 7.6K关注 0票数 2

我的应用程序不能自动显示entityManagerFactory。

我的applicationContext.xml

代码语言:javascript
复制
<tx:annotation-driven/>
<context:component-scan base-package="top.level.package" />

<bean id="persistenceUnitManager"     
    class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="persistenceXmlLocation">
        <value>classpath:jpa-persistence.xml</value>
    </property>
</bean>

<bean id="entityManagerFactory"      
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="persistenceUnitManager" />
</bean>

<bean id="transactionManager" 
    class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

我的java类

代码语言:javascript
复制
@Component
public class Engine {

    @Autowired
    @Qualifier("entityManagerFactory")
    private EntityManagerFactory entityManagerFactory;
......
}

问题:

为什么entityManagerFactory是空的?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-08-24 08:09:16

对于spring,要使用注释进行自动生成,您必须告诉spring。在您的xml配置中(假设您还没有context:component-scan元素)添加一个context:annotation-config。这将指示spring应用程序上下文扫描注释(如@Autowired@Inject@Resource等)。去做自动装配。

还要确保您希望将EntityManagerFactory注入( Engine类)的类是一个spring。Spring只会将引用注入spring托管bean。

票数 4
EN

Stack Overflow用户

发布于 2013-08-23 21:08:17

你试过这个吗?

代码语言:javascript
复制
private EntityManagerFactory entityManagerFactory;

@Autowired
@PersistenceUnit(unitName = "myUnitName")
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
    this.entityManagerFactory = entityManagerFactory;
}

不久前我也犯了同样的错误,我发现这是一个解决方案。

票数 3
EN

Stack Overflow用户

发布于 2013-08-24 09:37:33

如果您在Engine中使用new Engine() (如您的注释中所述),那么它不是由Spring来管理的。因此,@Component没有任何效果,也不会注入依赖项。你得注射引擎。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18411803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档