-1

i´m going to write a library that does some stuff and uses spring data.

The idea is that projects which uses this library can import this jar and use this library: MyLib.doSomeStuff().

It is possible to use Spring in this way and how can i initialize the ApplicationContext within the doSomeStuff() method, so that DI and the @Configuration Classes with the DataSources will be loaded?

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);
}
d4u7
  • 29
  • 5
  • You shouldn't initiate spring app context like this in your library. If you are building a library, make it a library and nothing else. Let the user decide on how create beans etc. You may provide xml or Java-based configuration to help the lib user configure Spring easier. – Adrian Shum Sep 12 '17 at 06:48

1 Answers1

0

If you have a root configuration class it can be as simple as

  ApplicationContext context = 
    new AnnotationConfigApplicationContext(GxConfig.class);

Just don't do it every time you call doStuff() as creating an application context is expensive. If you library is meant to be used as a black box, I guess it's ok to have this isolated application context.

You can do something like this:

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
  }

}
Strelok
  • 50,229
  • 9
  • 102
  • 115