Приложение Spring работает в Weblogi c 12.2.1.4. У меня есть 3 модуля.
Модуль 1 зависит от модуля 2 (хранилище 1), который зависит от модуля 3 (хранилище 2).
Модуль 1:
@Import(Module2Config.class)
@EnableAspectJAutoProxy
@SpringBootApplication
public class Application extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
SpringApplication.run(Application .class, args);
}
}
application.properties в модуле 1
java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory
java.naming.security.authentication=none
# DataSource
spring.datasource.jndi-name=jdbc/DS1
second.datasource.jndi-name=jdbc/DS2
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.generate-ddl=false
Module2Config.class находится в module2, который должен использовать по умолчанию автоматически настроенный источник данных пружины, выглядит следующим образом:
@Configuration
@EnableCaching
@EnableScheduling
@EnableJpaRepositories(basePackages = "package1.repository")
@EntityScan(basePackages = "package1.repository")
@Slf4j
@ComponentScan({"package1"})
@Import({Module3Config.class})
public class Module2Config {
@Value("${java.naming.factory.initial}")
private String INITIAL_CONTEXT_FACTORY;
private Properties getJNDiProperties() {
final Properties jndiProps = new Properties();
jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
return jndiProps;
}
@Bean(destroyMethod="")
public JndiTemplate jndiTemplate() {
final JndiTemplate jndiTemplate = new JndiTemplate();
jndiTemplate.setEnvironment(getJNDiProperties());
return jndiTemplate;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
}
И, наконец, Module3Config.class должен вручную создать источник данных, и он выглядит следующим образом :
@Configuration
@ComponentScan(basePackages = "package2")
@EnableJpaRepositories(basePackages = "package2")
@EntityScan(basePackages = "package2.model")
public class RepositoryConfig {
@Value("${second.datasource.jndi-name}")
private String dataSourceJndiname;
@Bean
public DataSource batchDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource(dataSourceJndiname);
}
@Bean
@Autowired
public PlatformTransactionManager transactionManager(DataSource dataSource) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory(dataSource).getObject());
return txManager;
}
@Bean
@Autowired
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setPackagesToScan("package2.model");
factoryBean.setDataSource(dataSource);
factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
return factoryBean;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setShowSql(true);
return jpaVendorAdapter;
}
@Bean
@Autowired
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
Ошибка при развертывании в Weblogi c.
Сначала не удается найти объекты из Module2Config.class при попытке инициализировать JPA EntitiManagerFactory для модуля персистентности «default»
j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityWebService' defined in URL [zip:C:/.../AdminServer/tmp/_WL_user/app_war/b9sjq7/war/WEB-INF/lib/_wl_cls_gen.jar!/module1package/service/cases/EntityWebService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityServiceImpl' defined in URL [zip:C:/...tmp/_WL_user/app_war/b9sjq7/war/WEB-INF/lib/service-1.2.0-SNAPSHOT.jar!/package1/f1/EntityServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'listEntities': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class package1.repository.Entity1
Короче говоря, он не нашел package1.repository.Entity1
...creating bean with name 'entityWebService' ...
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException:
Not a managed type: class package1.repository.Entity1
Во-вторых, сбой при инициализации контекста:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthEndpoint]: Factory method 'healthEndpoint' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthIndicatorAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthIndicatorAutoConfiguration$$EnhancerBySpringCGLIB$$e3f909d1]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'batchDataSource' defined in eu.europa.ec.comp.cmr.iop.repository.config.RepositoryConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'batchDataSource' threw exception; nested exception is org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'jdbc/DS2'; nested exception is javax.naming.NameNotFoundException: Unable to resolve 'jdbc.DS2'. Resolved 'jdbc'; remaining name 'DS2'
, короче:
Failed to look up JNDI DataSource with name 'jdbc/DS2'; nested exception is
javax.naming.NameNotFoundException: Unable to resolve 'jdbc.DS2'. Resolved 'jdbc'; remaining name 'DS2'
Итак, он не нашел сущность из модуля 2 и не разрешил имя jndi для DS2.
ВТОРОЙ ВОПРОС:
При весенней загрузке, если она находится под Weblogi c, вы не должны ed, чтобы определить диспетчер транзакций для источника данных, потому что это сделано, и он использует один из Weblogi c. Итак, для второго источника данных я должен определить его вручную или я могу оставить его для автоматической загрузки?