-1

몇 가지 작업을 수행하고 스프링 데이터를 사용하는 라이브러리를 작성하려고합니다.스프링 데이터를 사용하는 Java 라이브러리

아이디어는이 라이브러리를 사용하는 프로젝트가이 jar를 가져 와서이 라이브러리를 사용할 수 있다는 것입니다. MyLib.doSomeStuff().

이런 식으로 Spring을 사용할 수 있으며 doSomeStuff() 메서드 내에서 ApplicationContext를 초기화하여 DataSources의 DI 및 @Configuration 클래스를로드 할 수 있습니까? 당신이

ApplicationContext context = 
    new AnnotationConfigApplicationContext(GxConfig.class); 

은 그냥 당신이 응용 프로그램 컨텍스트를 만드는 등의 doStuff()를 호출 할 때마다하지 않는다 간단

로 될 수있는 루트 구성 클래스가있는 경우

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); 
} 
+0

당신은 당신의 라이브러리에이 같은 스프링 애플리케이션 컨텍스트를 시작해서는 안된다. 도서관을 짓고 있다면 도서관과 다른 곳으로 만들 수 있습니다. 사용자가 bean 작성 등을 결정하도록하십시오. lib 사용자가 Spring을 더 쉽게 구성 할 수 있도록 xml 또는 Java 기반 구성을 제공 할 수 있습니다. –

답변

0

는 비싸다. 라이브러리를 블랙 박스로 사용하려는 경우이 분리 된 응용 프로그램 컨텍스트를 갖는 것이 좋습니다.

당신은 같은 것을 할 수 있습니다

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 
    } 

} 
관련 문제