How to get ServiceRegistry instance from Spring Boot application? - spring-boot

I am trying to use a CommandLineRunner to access info on the underlying Hibernate database so I can eventually dump a schema file. I need to get access to the service registry instance to do that.
I tried to see if I can get it from the AutoWired EntityManagerFactory via this code:
package test;
import javax.persistence.EntityManagerFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.ServiceRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class AutoWiredTest implements CommandLineRunner {
#Autowired
private EntityManagerFactory emf;
#Override
public void run(String... args)
throws Exception {
SessionFactoryImplementor sessionFactory = emf.unwrap(SessionFactoryImplementor.class);
ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
if( serviceRegistry == null )
throw new Exception("Service registry is null");
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.buildMetadata();
}
The application gives me this error:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:780) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:761) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:310) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.4.jar:2.6.4]
at test.AutoWiredTest.main(AutoWiredTest.java:31) ~[classes/:na]
Caused by: org.hibernate.HibernateException: Unexpected type of ServiceRegistry [org.hibernate.service.internal.SessionFactoryServiceRegistryImpl] encountered in attempt to build MetadataBuilder
at org.hibernate.boot.internal.MetadataBuilderImpl.getStandardServiceRegistry(MetadataBuilderImpl.java:113) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at org.hibernate.boot.internal.MetadataBuilderImpl.<init>(MetadataBuilderImpl.java:93) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:146) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at org.hibernate.boot.MetadataSources.buildMetadata(MetadataSources.java:202) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at test.AutoWiredTest.run(AutoWiredTest.java:26) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:777) ~[spring-boot-2.6.4.jar:2.6.4]
... 5 common frames omitted
Next, I tried to create a builder with this code:
package test;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BuilderTest implements CommandLineRunner {
#Override
public void run(String... args)
throws Exception {
new StandardServiceRegistryBuilder().configure().build();
}
public static void main(String[] args)
throws Exception {
SpringApplication.run(test.BuilderTest.class, args);
}
}
Which resulted in this error:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:780) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:761) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:310) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.4.jar:2.6.4]
at test.BuilderTest.main(BuilderTest.java:18) ~[classes/:na]
Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:254) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:243) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at test.BuilderTest.run(BuilderTest.java:13) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:777) ~[spring-boot-2.6.4.jar:2.6.4]
... 5 common frames omitted
It is looking for a cfg.xml file, but I have already defined my database configuration in the application.properties file:
hibernate.current_session_context_class=thread
hibernate.format_sql=false
hibernate.show_sql=false
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/marketing
spring.datasource.username=marketing
spring.datasource.password=[PASS]
spring.logging.level.root=ERROR
spring.logging.level.org.hibernate=INFO
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDB103Dialect
Any ideas what is going wrong?

Seems like Spring just doesn't register Hibernate ServiceRegistry as a bean. I looked through the sources and discover that its instance is created inside the SessionFactoryImpl constructor.
You can try to apply this hack.
#SpringBootApplication
public class AutoWiredTest implements CommandLineRunner {
#Autowired
private EntityManagerFactory emf;
#Override
public void run(String... args)
throws Exception {
SessionFactoryImplementor sessionFactory = emf.unwrap(SessionFactoryImplementor.class);
ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
}
public static void main(String[] args)
throws Exception {
SpringApplication.run(AutoWiredTest.class, args);
}
}

Related

Caused by: java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one

I am upgrading spring boot 2.5.12 to Spring boot 2.7.2 in gradle kotlin. As per the link given <https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter > . When I have removed deprecated websecurityconfigureradapter getting exception. Code snippet is given below
#Configuration
#EnableWebSecurity
#Order(1)
public class BasicAuthC {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/api/anything"")
.and()
.authorizeRequests(requests -> requests.anyRequest().fullyAuthenticated())
.httpBasic()
return http.build();
}
#Bean
public InMemoryUserDetailsManager memoryUserDetailsManager() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
return new InMemoryUserDetailsManager (User.withUsername("testUserName").password(encoder.encode("****")).
authorities(new SimpleGrantedAuthority("SOME_ROLE")).build());
}
}
import com.azure.spring.aad.webapi.AADJwtBearerTokenAuthenticationConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
#Order(2)
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Configuration
public class OAuthTwoConfiguration {
#Profile(value="OAUTHPROFILE")
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/test").permitAll()
.and().authorizeRequests((requests) -> requests.anyRequest().authenticated())
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(new AADJwtBearerTokenAuthenticationConverter());
return http.build();
}
#Profile(value = "test")
#Bean
public WebSecurityCustomizer WebSecurityCustomizer () throws Exception {
return (web)->web.ignoring().antMatchers("/someAPI");
}
}
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.22.jar:5.3.22]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.22.jar:5.3.22]
... 21 common frames omitted
Caused by: java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.
at org.springframework.util.Assert.state(Assert.java:76) ~[spring-core-5.3.22.jar:5.3.22]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:106) ~[spring-security-config-5.7.2.jar:5.7.2]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.22.jar:5.3.22]
... 22 common frames omitted
Either your code or some of the libraries that you use are still providing WebSecurityConfigurerAdapter.
Check your code again, maybe you are forgetting some place.
Try to update the libraries that you use to the latest versions.
If they are not migrated yet, you'll might have to wait until they are, before you get rid of WebSecurityConfigurerAdapter.

how to fix the error "error creating bean with name...."

when I run my application there is the following error displayed:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pamdaBatchConfigurer': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getJobRepository' defined in com.orange.pamda.config.PamdaBatchConfigurer: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.repository.JobRepository]: Circular reference involving containing bean 'pamdaBatchConfigurer' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getJobRepository' threw exception; nested exception is java.lang.IllegalArgumentException: DatabaseType not found for product name: [MariaDB]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4685)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5146)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:343)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:474)
here is my file "pamdabatchconfigurer.java":
package com.orange.pamda.config;
import java.util.Date;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.JobExplorerFactoryBean;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import com.orange.pamda.config.batch.listener.SendFileAfterExportListener;
import com.orange.pamda.worker.config.CatalogueExporterJobConfiguration;
import com.orange.pamda.worker.config.CatalogueImporterJobConfiguration;
import com.orange.pamda.worker.config.CommonJobConfiguration;
import com.orange.pamda.worker.config.DataExporterJobConfiguration;
import com.orange.pamda.worker.config.HierarchyValidatorJobConfiguration;
import com.orange.pamda.worker.config.JobBuilderFactory;
import com.orange.pamda.worker.config.KoalaExporterJobConfiguration;
import com.orange.pamda.worker.config.MappingExporterJobConfiguration;
import com.orange.pamda.worker.config.MappingImporterJobConfiguration;
import com.orange.pamda.worker.config.OrphanExporterJobConfiguration;
import com.orange.pamda.worker.config.ReleaseJobConfiguration;
import com.orange.pamda.worker.config.SummaryExporterJobConfiguration;
#Configuration
#EnableBatchProcessing(modular = true)
#Import({ CommonJobConfiguration.class, CatalogueExporterJobConfiguration.class,
CatalogueImporterJobConfiguration.class, DataExporterJobConfiguration.class,
HierarchyValidatorJobConfiguration.class, KoalaExporterJobConfiguration.class,
MappingExporterJobConfiguration.class, MappingImporterJobConfiguration.class,
OrphanExporterJobConfiguration.class, ReleaseJobConfiguration.class, SummaryExporterJobConfiguration.class })
public class PamdaBatchConfigurer implements BatchConfigurer {
#Autowired
private PlatformTransactionManager transactionManager;
#Autowired
private DataSource dataSource;
#Override
#Bean
public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
jobRepositoryFactoryBean.setDataSource(dataSource);
jobRepositoryFactoryBean.setTransactionManager(transactionManager);
jobRepositoryFactoryBean.setIsolationLevelForCreate("ISOLATION_DEFAULT");
jobRepositoryFactoryBean.afterPropertiesSet();
return jobRepositoryFactoryBean.getObject();
}
#Override
public PlatformTransactionManager getTransactionManager() throws Exception {
return transactionManager;
}
#Override
#Bean
public JobLauncher getJobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(getJobRepository());
// jobLauncher.setTaskExecutor(getTaskExecutor());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
#Override
#Bean
public JobExplorer getJobExplorer() throws Exception {
JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
jobExplorerFactoryBean.setDataSource(dataSource);
jobExplorerFactoryBean.afterPropertiesSet();
return jobExplorerFactoryBean.getObject();
}
// #Bean
// public TaskExecutor getTaskExecutor() {
// SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new
// SimpleAsyncTaskExecutor();
// simpleAsyncTaskExecutor.setConcurrencyLimit(1000); // no throttle
// return simpleAsyncTaskExecutor;
// }
#Bean
public JobBuilderFactory getJobBuilderFactory() throws Exception {
return new JobBuilderFactory(getJobRepository(), sendFileAfterExportListener());
}
#Bean
public StepBuilderFactory getStepBuilderFactory() throws Exception {
return new StepBuilderFactory(getJobRepository(), transactionManager);
}
#Bean
public SendFileAfterExportListener sendFileAfterExportListener() {
return new SendFileAfterExportListener();
}
#PostConstruct
#Transactional
public void init() throws Exception {
JobExplorer jobExplorer = getJobExplorer();
JobRepository jobRepository = getJobRepository();
for (String jobName : jobExplorer.getJobNames()) {
Set<JobExecution> runningJobExecutions = jobExplorer.findRunningJobExecutions(jobName);
for (JobExecution runningJobExecution : runningJobExecutions) {
runningJobExecution.setExitStatus(ExitStatus.UNKNOWN);
runningJobExecution.setEndTime(new Date());
jobRepository.update(runningJobExecution);
}
}
}
}
I really do not know where this error comes from can someone help me please?
Most important part of the stacktrace: DatabaseType not found for product name: [MariaDB]
Look here: https://github.com/spring-projects/spring-framework/issues/22344
Similar issues:
DatabaseType not found for product name: [Impala]
Spring batch --- DatabaseType not found for product name: [Informix Dynamic Server]
Could you please check this part of the exception, that you have added. It might be the reason : "Circular reference involving".
Circular reference involving containing bean 'pamdaBatchConfigurer' -
consider declaring the factory method as static for independence from
its containing instance.

Spring boot 2 - Unable to register and use JNDI in embedded tomcat container

I am using spring boot 2.0.0.RELEASE and trying to register a JNDI in embedded tomcat container.
Below is my spring boot starter class-
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.ContextResource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
#Bean
public ServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
#Override
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
tomcat.enableNaming();
return new TomcatWebServer(tomcat, getPort() >= 0);
}
#Override
protected void postProcessContext(Context context) {
ContextResource resource = new ContextResource();
resource.setName("java:comp/env/jdbc/OracleDSNonXA");
resource.setType(DataSource.class.getName());
resource.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver");
resource.setProperty("url", "DBURL");
resource.setProperty("username", "DBUSER");
resource.setProperty("password", "PASSWORD");
context.getNamingResources().addResource(resource);
}
};
}
}
My spring configuration class is as follows-
#Configuration
#PropertySource("/hibernate-settings.properties")
#EnableTransactionManagement
public class ApplicationConfig {
/*Logic to load values from property file here*/
#Bean
public JpaVendorAdapter hibernateJpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
#Bean
public LocalContainerEntityManagerFactoryBean myentityManagerFactory(DataSource mydataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(mydataSource);
emf.setJpaVendorAdapter(hibernateJpaVendorAdapter());
emf.setPersistenceUnitName("mydbunit");
Properties jpaProperties= new Properties();
jpaProperties.setProperty("hibernate.dialect", dialectValue);
jpaProperties.setProperty("hibernate.transaction.manager_lookup_class", trxManagerLookupClass);
jpaProperties.setProperty("hibernate.generate_statistics", generateStatistics);
jpaProperties.setProperty("hibernate.show_sql", showSql);
jpaProperties.setProperty("hibernate.format_sql", formatSql);
emf.setJpaProperties(jpaProperties);
emf.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return emf;
}
#Bean(destroyMethod = "")
public DataSource jndiDataSource() throws IllegalArgumentException,
NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/OracleDSNonXA");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource) bean.getObject();
}
#Bean
public BeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
}
I am primarily getting the exception-
Caused by: org.springframework.jndi.JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object; nested exception is javax.naming.NameNotFoundException: Name [jdbc/OracleDSNonXA] is not bound in this Context. Unable to find [jdbc]
Below is detailed exception trace.
2018-03-16 13:22:59.450 WARN 4892 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myentityManagerFactory' defined in class path resource [com/alj/mypage/config/ApplicationConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: mydbunit] Unable to build Hibernate SessionFactory
2018-03-16 13:22:59.452 INFO 4892 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-03-16 13:22:59.468 INFO 4892 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-03-16 13:22:59.474 ERROR 4892 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myentityManagerFactory' defined in class path resource [com/alj/mypage/config/ApplicationConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: mydbunit] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1085) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:858) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at com.alj.mypage.config.MySpringBootApplication.main(MySpringBootApplication.java:19) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: mydbunit] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:970) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
I am very new to Spring boot and I am not sure what configuration I have missed.

Class loading error on websphere when upgrading to Spring 4.2.3

When I upgrade a multi-war Spring application from Spring 4.1.8 to 4.2.3 I get a strange ClassNotFoundException in a websphere application server (version 8.5.5). The class that is not found by the classloader is on the classpath and was found with previous releases of Spring.
[11.12.15 10:04:27:536 CET] 0000004f FfdcProvider W com.ibm.ws.ffdc.impl.FfdcProvider logIncident FFDC1003I: FFDC Incident emitted on D:\devsbb\websphere\was8_5\IBM\WebSphere\AppServer\profiles\AppSrv01\logs\ffdc\server1_bc0c2481_15.12.11_10.04.27.4771875357035970693584.txt com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated 1341
[11.12.15 10:04:27:536 CET] 0000004f webapp E com.ibm.ws.webcontainer.webapp.WebApp notifyServletContextCreated SRVE0283E: Exception caught while initializing context: {0}
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'showCaseViewModel' defined in BeanDefinition defined in file [D:\devsbb\websphere\was8_5\IBM\WebSphere\AppServer\profiles\AppSrv01\installedApps\localhostNode01Cell\template-ear-4.0.3-SNAPSHOT.ear\template-web-jsf.war\WEB-INF\classes\ch\sbb\myapp\presentation\ShowCaseViewModel.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:1689)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:414)
at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88)
at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:169)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:749)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:634)
at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:426)
at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:718)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1177)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1370)
at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:639)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:968)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:776)
at com.ibm.ws.runtime.component.ApplicationMgrImpl$5.run(ApplicationMgrImpl.java:2195)
at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5474)
at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5600)
at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2200)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:389)
at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:332)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:119)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$CUInitializer.run(CompositionUnitMgrImpl.java:938)
at com.ibm.wsspi.runtime.component.WsComponentImpl$_AsynchInitializer.run(WsComponentImpl.java:502)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1864)
Caused by: org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:218)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
at org.springframework.aop.scope.ScopedProxyFactoryBean.setBeanFactory(ScopedProxyFactoryBean.java:111)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1565)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
... 36 more
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.asm.ClassWriter.getCommonSuperClass(ClassWriter.java:1684)
at org.springframework.asm.ClassWriter.getMergedType(ClassWriter.java:1654)
at org.springframework.asm.Frame.merge(Frame.java:1426)
at org.springframework.asm.Frame.merge(Frame.java:1337)
at org.springframework.asm.MethodWriter.visitMaxs(MethodWriter.java:1475)
at org.springframework.cglib.core.CodeEmitter.visitMaxs(CodeEmitter.java:842)
at org.springframework.cglib.transform.impl.UndeclaredThrowableTransformer$1.visitMaxs(UndeclaredThrowableTransformer.java:56)
at org.springframework.cglib.core.CodeEmitter.visitMaxs(CodeEmitter.java:842)
at org.springframework.cglib.core.CodeEmitter.end_method(CodeEmitter.java:138)
at org.springframework.cglib.proxy.MethodInterceptorGenerator.generate(MethodInterceptorGenerator.java:131)
at org.springframework.cglib.proxy.Enhancer.emitMethods(Enhancer.java:1005)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:509)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:231)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:55)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:202)
... 41 more
Here is my class:
package ch.sbb.myapp.presentation;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.sbb.esta.core.stereotype.Scope;
import ch.sbb.esta.core.stereotype.web.EstaViewModel;
import ch.sbb.esta.core.type.Email;
import ch.sbb.myapp.exception.TemplateErrorCode;
import ch.sbb.myapp.model.Customer;
import ch.sbb.myapp.model.CustomerStatus;
import ch.sbb.myapp.model.i18n.I18nMessageKey;
import ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException;
/**
* ViewModel für den Primefaces Showcase.
*/
#EstaViewModel(scope = Scope.REQUEST)
public class ShowCaseViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ShowCaseViewModel.class);
public boolean isMcaIntegrationInClasspath() {
try {
this.getClass().getClassLoader().loadClass("ch.sbb.myapp.presentation.McaDemoViewModel");
return true;
} catch (ClassNotFoundException e) { // NOSONAR: is just a check whether MCA integration is on the classpath
return false;
}
}
public CustomerStatus getCustomerStatusNull() {
return null;
}
public void setCustomerStatusNull(CustomerStatus t) {
}
public CustomerStatus getCustomerStatus() {
return CustomerStatus.VIP;
}
public void throwEstaException() throws SampleTranslateableFileCopyException {
throw new SampleTranslateableFileCopyException(I18nMessageKey.ERROR_WHILE_CALLING_SERVICE,
TemplateErrorCode.FILE_COPY_ERROR_CODE, "fileA", "fileB");
}
public void logValidationException() {
Customer wrongCustomer = new Customer("fi", "la", new Email("bla#sbb.ch"));
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Customer>> violations = validator.validate(wrongCustomer);
Set<ConstraintViolation<?>> violationsWithoutType = new HashSet<>();
violationsWithoutType.addAll(violations);
LOGGER.warn("violated exception", new ConstraintViolationException("bla", violationsWithoutType));
}
}
The annotation #EstaViewModel is declared as a simple #Component:
#Inherited
#Component
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.TYPE })
public #interface EstaViewModel {
String value() default "";
Scope scope() default Scope.REQUEST;
}
All other classes with the #EstaViewModel annotation are initialized without any problem.
Any ideas?

Adding custom behavior to all repositories without xml configuration

I am trying to add custom behavior to all repositories in my spring application but I don't want to use XML configuration, only spring annotation like #xxxx.
So I looked for that on the Internet and I found this documentation.
The problem with the documentation is that it deals with JPA (not MongoDB) and the step 4 is not specific enough for a spring application without xml annotation.
Documentation step 4 :
declare beans of the custom factory directly
How we do that?
So I didn't give up and I looked deeper on the Internet and I found this.
But this time, it was for Solr (not Mongo).
The interesting part is:
import org.springframework.context.annotation.Configuration;
import org.springframework.data.solr.repository.config.EnableSolrRepositories;
#Configuration
#EnableSolrRepositories(
basePackages = "net.petrikainulainen.spring.datasolr.todo.repository.solr",
repositoryFactoryBeanClass = CustomSolrRepositoryFactoryBean.class
)
public class SolrContext {
//Configuration is omitted.
}
But my application still does not work! You can find all the code in github.
Architecture
src/main/java
fr.exemple.test.Application.java
fr.exemple.test.controller.TestController.java
fr.exemple.test.model.domain.Test.java
fr.exemple.test.model.repository.TestRepository.java
fr.exemple.test.model.repository.global.MyRepository.java
fr.exemple.test.model.repository.global.MyRepositoryFactoryBean.java
fr.exemple.test.model.repository.global.MyRepositoryImpl.java
My Code
Application :
package fr.exemple.test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import fr.exemple.test.model.repository.global.MyRepositoryFactoryBean;
#Configuration
#ComponentScan
#EnableAutoConfiguration
#EnableMongoRepositories(
basePackages = {"fr.exemple.test.repository.global"},
repositoryFactoryBeanClass = MyRepositoryFactoryBean.class
)
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
app.run(args);
}
}
TestController :
package fr.exemple.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import fr.exemple.test.model.repository.TestRepository;
#RestController
#RequestMapping("/test")
public class TestController {
#Autowired
private TestRepository repository;
#RequestMapping(method=RequestMethod.GET)
public void sharedCustomMethodTest() {
repository.sharedCustomMethod("Hello World !");
}
}
Test :
package fr.exemple.test.model.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Test {
#Id
private String id;
private String firstName;
private String lastName;
public Test() {}
public Test(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
TestRepository :
package fr.exemple.test.model.repository;
import fr.exemple.test.model.domain.Test;
import fr.exemple.test.model.repository.global.MyRepository;
public interface TestRepository extends MyRepository<Test, String> {
}
MyRepository :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.NoRepositoryBean;
#NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends MongoRepository<T, ID>{
void sharedCustomMethod(ID id);
}
MyRepositoryFactoryBean :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
public class MyRepositoryFactoryBean<R extends MongoRepository<T, I>, T, I extends Serializable>
extends MongoRepositoryFactoryBean<R, T, I> {
#Override
protected RepositoryFactorySupport getFactoryInstance(MongoOperations operations) {
return new MyRepositoryFactory<T, I>(operations);
}
private static class MyRepositoryFactory<T, I extends Serializable> extends
MongoRepositoryFactory {
private MongoOperations mongoOperations;
public MyRepositoryFactory(MongoOperations mongoOperations) {
super(mongoOperations);
this.mongoOperations = mongoOperations;
}
protected Object getTargetRepository(RepositoryMetadata metadata) {
TypeInformation<T> information = ClassTypeInformation.from((Class<T>)metadata.getDomainType());
MongoPersistentEntity<T> pe = new BasicMongoPersistentEntity<T>(information);
MongoEntityInformation<T,I> mongometa = new MappingMongoEntityInformation<T, I>(pe);
return new MyRepositoryImpl<T, I>(mongometa, mongoOperations);
}
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return MyRepository.class;
}
}
}
MyRepositoryImpl :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;
public class MyRepositoryImpl<T, ID extends Serializable> extends
SimpleMongoRepository<T, ID> implements MyRepository<T, ID> {
private Log log = LogFactory.getLog(MyRepositoryImpl.class);
private MongoOperations mongoOperations;
public MyRepositoryImpl(MongoEntityInformation<T, ID> metadata,
MongoOperations mongoOperations) {
super(metadata, mongoOperations);
this.mongoOperations = mongoOperations;
}
#Override
public void sharedCustomMethod(ID id) {
log.info(id);
}
}
Stack Trace
Error starting ApplicationContext. To display the auto-configuration report enabled debug logging (start with --debug)
2014-07-13 11:12:51.951 ERROR 2144 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at fr.exemple.test.Application.main(Application.java:23)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 14 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 16 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:82)
at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:52)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:128)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 26 common frames omitted
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at fr.exemple.test.Application.main(Application.java:23)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 14 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 16 more
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:82)
at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:52)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:128)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 26 more
This happens as the package structure is not consistent. The base package of #EnableMongoRepositories points to fr.exemple.test.repository.global whereas the repository definition is located in fr.exemple.test.model.repository. As the scan for repositories returns without any result boot auto configuration, at this point not knowing of any custom RepositoryFactoryBean definitions, kicks in, enabling repositories on fr.exemple.test where Application resides.
So you could update your package structure.
Or make boot aware of MyRepositoryFactoryBean by registering it in your context via #Component and remove #EnableMongoRepositories so that scanning for a bean of type RepositoryFactoryBeanSupport can pick up the config.
When you declare #EnableMongoRepositories please take a look at availables options. One of them is :
public abstract Class<?> repositoryFactoryBeanClass
Returns the FactoryBean class to be used for each repository instance.
Defaults to MongoRepositoryFactoryBean.
Returns:
Default:
org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.class
so i.e
#EnableMongoRepositories(repositoryFactoryBeanClass=YourMongoCustomRepositoryFactoryBean.class)

Resources