使用Spring Data的Java库

时间:2017-09-04 13:07:50

标签: java spring dependency-injection datasource applicationcontext

我要编写一个可以执行某些操作并使用spring数据的库。

这个想法是使用这个库的项目可以导入这个jar并使用这个库:MyLib.doSomeStuff()。

可以这样使用Spring,如何在doSomeStuff()方法中初始化ApplicationContext,以便加载DI和带有DataSources的@Configuration类?

public class MyLib {

@Autowired
private static SomeJpaRepository someJpaRepository;

  public static void doSomeStuff(){
    ...init ApplicationContext....
    ...setup DataSources...
    List<SomeEntity> someEntityList = someJpaRepository.someMethod();
  }

// or
  public static List<SomeEntity> getSomeEntityList() {
    return someJpaRepository.finAll();
  }
}

//other package
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "gxEntityManager", transactionManagerRef = "gxTransactionManager",
        basePackages = "com.gx")
public class GxConfig {

  @Primary
  @Bean(name = "gxDataSource")
  public DataSource gxDataSource() {
    DataSourceBuilder dataSourceBuilderGx = null;
    //..
    return dataSourceBuilderGx.build();
  }

  @Primary
  @Bean(name = "gxEntityManager")
  public LocalContainerEntityManagerFactoryBean gxEntityManagerFactory(EntityManagerFactoryBuilder builder) {
    return builder.dataSource(gxDataSource()).packages("com.gx").build();
 }

  @Primary
  @Bean(name = "gxTransactionManager")
  public PlatformTransactionManager gxTransactionManager(
        @Qualifier("gxEntityManager") EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
  }
}

//other package
public interface SomeEntity extends JpaRepository<SomeEntity, Long>
{
    SomeEntity findById(Long id);
}

1 个答案:

答案 0 :(得分:0)

如果您有根配置类,它可以像

一样简单
  ApplicationContext context = 
    new AnnotationConfigApplicationContext(GxConfig.class);

每次拨打doStuff()时都不要这样做,因为创建应用程序上下文很昂贵。如果您的库被用作黑盒子,我想可以拥有这个独立的应用程序上下文。

您可以这样做:

public class MyLib {

  private ApplicationContext context;

  public MyLib() {
    context = new AnnotationConfigApplicationContext(GxConfig.class);
  }

  public void doStuff() {
    SomeBean bean = context.getBean(SomeBean.class);
    // do something with the bean
  }

}