0

以下情况。我想使用 spring-data 因为我喜欢 Domain JpaRepository(interface) 系统。

但是,我不想使用 Spring-Framework 本身。我想坚持 javax.* ejb3 规范

我正在尝试设置项目配置。

我有一个代表持久层的 spring-data-jpa 项目。我使用@Stateless 而不是弹簧@Service 和@Inject 而不是@autowired(因为我听说那里有同义词。持久层内的Accountservice 仅用于测试目的。

PersistanceModule(Eclipseproject)
|
|-com.ns.persistance
|   |-domain
|       |-Account
|   |-repository
|       |-AccountRepository (JpaRepositry interface)
|   |-test
|       |-AccountService (which contains a method do save a user in the database)

帐户存储库

public interface AccountRepository extends JpaRepository<Account, Long> { 

    Account findByUsername(String username);

}

用于测试目的的帐户服务。

@Stateless
public class AccountService {

    @Inject
    private AccountRepository ar;

    public void createTestAccount() {
        Account account = new Account();
        account.setUsername("testAccount");
        account.setPassword("sicheres passwort");
        account.setEmail("kks.cs@web.de");
        account.setCreationTime(new Date());
        account.setLastModificationDate(new Date());

        account = ar.save(account);

    }
}

测试弹簧数据的工作

@Singleton
public class SSService {

    @EJB
    AccountService as;

    @Schedule(minute = "*/5", hour = "*", persistent = false)
    public void doWork() {

        System.out.println("WorkJob!!!!!!!");
        //as.createTestAccount();

    }

}

我有一个 spring-data-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 
   xmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:jpa="http://www.springframework.org/schema/data/jpa"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/data/jpa 
      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <jpa:repositories base-package="com.ns.persistence.repository" />

</beans>

JBoss 一直告诉我 AccountService 为 NULL(Nullpointer)。我相信我忘了设置一些配置,但我无法掌握它,谷歌搜索不断让我得到简单的 Springframework 解决方案。我的问题:我错过了什么?spring 数据是否适用于 EJB(javax) 或者我是否需要使用 springframework。

4

1 回答 1

0

只是为了确保你做对了。要使用 Spring Data JPA,您需要使用 Spring 框架。您不一定需要使用容器(XML 配置、容器设置),但您需要应用程序类路径上的 Spring JAR。

从版本 1.1.0.RC1(已经发布)开始,Spring Data JPA 项目支持在 CDI 容器中运行,而 JBoss AS7 就是其中一个实例。因此,有了刚才提到的版本的 Spring Data JPA,这应该可以工作。然后不需要 Spring 配置文件,只需要beans.xmlCDI 指定的空文件。

如果您使用的是早期版本,则必须编写一些代码来自己实例化存储库实例:

 @Stateless
 class YourService {

   @PersistenceContext
   private EntityManager em;

   private AccountRepository repository

   @PostConstruct
   public void init() {
      RepositoryFactorySupport factory = new JpaRepositoryFactory(em);
      this.repository = factory.getRepository(AccountRepository.class);
   }
}

将该代码放入一个公共组件中并让该实例注入服务然后避免在每个服务实现中重写此设置代码可能是有意义的。正如我上面提到的:在即将到来的 1.1.0 版本中,这将是开箱即用的。

于 2012-05-01T17:10:30.660 回答