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

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.

Related

How to get ServiceRegistry instance from Spring Boot application?

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

SpringBoot can't find EntityManagerFactory even though it is declared

I have this code for SpringBoot. It loads both mybatis and hibernate. I'm getting an exception about a bean of type EntityManagerFactory not available, but it is defined here. The logging outputs containing 'xxx' all print.
package com.ritchey.timesheet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.hibernate.SessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jndi.JndiTemplate;
import org.springframework.orm.hibernate5.HibernateExceptionTranslator;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "org.browsexml.timesheetjob")
#ComponentScan(basePackages = "org.browsexml.timesheetjob")
#MapperScan(basePackages = "com.ritchey.timesheet.mapper.TimeSheet", sqlSessionTemplateRef="TimeSheetSqlSessionTemplate")
#MapperScan(basePackages = "com.ritchey.timesheet.mapper.powercampus", sqlSessionTemplateRef="powercampusSqlSessionTemplate")
#SpringBootApplication()
public class Timesheet {
private static final Logger LOGGER = LoggerFactory.getLogger(Timesheet.class);
static public String version = "77777";
public static void main(String[] args) throws NamingException {
SpringApplication application = new SpringApplication(Timesheet.class);
LOGGER.info("RUN TIMESHEET ");
ApplicationContext ctx = application.run();
LOGGER.info("messages TIMESHEET");
String basename = ctx.getEnvironment().getProperty("spring.messages.basename", "messages");
LOGGER.info("basename = " + basename);
LOGGER.info("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
LOGGER.info(beanName);
}
}
#Bean
public DataSource getCampusDatasource() throws NamingException {
JndiTemplate jndiTemplate = new JndiTemplate();
DataSource ds = null;
ds = (DataSource) jndiTemplate.lookup("java:comp/env/jdbc/powerCampus");
return ds;
}
#Bean
#Primary
public DataSource getTimeSheetDatasource() throws NamingException {
JndiTemplate jndiTemplate = new JndiTemplate();
DataSource ds = null;
ds = (DataSource) jndiTemplate.lookup("java:comp/env/jdbc/TimeSheet");
return ds;
}
#Bean
public SqlSessionFactory TimeSheetSqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(getTimeSheetDatasource());
return factoryBean.getObject();
}
#Bean
#Primary
public SqlSessionFactory powercampusSqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(getCampusDatasource());
return factoryBean.getObject();
}
#Bean
#Primary
public SqlSessionTemplate TimeSheetSqlSessionTemplate(#Qualifier("TimeSheetSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
#Bean
#Primary
public SqlSessionTemplate powercampusSqlSessionTemplate(#Qualifier("powercampusSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
#Bean
#Primary
public SessionFactory sessionFactory() throws Exception {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(getTimeSheetDatasource());
factoryBean.setMappingResources("org/browsexml/timesheetjob/model/Awards.hbm.xml",
"org/browsexml/timesheetjob/model/HoursWorked.hbm.xml",
"org/browsexml/timesheetjob/model/Job.hbm.xml",
"org/browsexml/timesheetjob/model/PeopleProperties.hbm.xml",
"org/browsexml/timesheetjob/model/CodeTerm.hbm.xml",
"org/browsexml/timesheetjob/model/Holiday.hbm.xml",
"org/browsexml/timesheetjob/model/PayPer.hbm.xml",
"org/browsexml/timesheetjob/model/Awarded.hbm.xml",
"org/browsexml/timesheetjob/model/Agreements.hbm.xml",
"org/browsexml/timesheetjob/model/Timesheets.hbm.xml",
"org/browsexml/timesheetjob/model/FulltimeAgreements.hbm.xml",
"org/browsexml/timesheetjob/model/Supervisor.hbm.xml"
);
factoryBean.setAnnotatedClasses(org.browsexml.timesheetjob.model.WorkCode.class
, org.browsexml.timesheetjob.model.ProcessErrors.class
, org.browsexml.timesheetjob.model.UserLog.class
, org.browsexml.timesheetjob.model.Properties.class
, org.browsexml.timesheetjob.model.AuditTrail.class
, org.browsexml.timesheetjob.model.PositionCode.class
, org.browsexml.timesheetjob.model.Position.class
, org.browsexml.timesheetjob.model.CodeRegions.class);
Properties p = new Properties();
p.setProperty("hibernate.dialect", "org.browsexml.dialect.SQLServerDialect");
p.setProperty("hibernate.hbm2ddl.auto", "validate");
p.setProperty("hibernate.query.substitutions", "true 1; false 0; yes 'Y'; no 'N'; year dbo.year");
p.setProperty("hibernate.show_sql", "true");
factoryBean.setHibernateProperties(p);
return factoryBean.getObject();
}
#Bean
public SessionFactory pcSessionFactory() throws Exception {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(getCampusDatasource());
factoryBean.setMappingResources(
"org/browsexml/timesheetjob/model/PeopleBasic.hbm.xml",
"org/browsexml/timesheetjob/model/Address.hbm.xml"
);
Properties p = new Properties();
p.setProperty("hibernate.dialect", "org.browsexml.dialect.SQLServerDialect");
p.setProperty("hibernate.hbm2ddl.auto", "validate");
p.setProperty("hibernate.query.substitutions", "true 1; false 0; yes 'Y'; no 'N'; year dbo.year");
p.setProperty("hibernate.show_sql", "true");
factoryBean.setHibernateProperties(p);
return factoryBean.getObject();
}
#Bean(name="entityManagerFactory")
public EntityManagerFactory entityManagerFactory() throws SQLException, NamingException {
LOGGER.debug("xxx entity manager factory");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
vendorAdapter.setGenerateDdl(true);
HibernateJpaDialect jpd = new HibernateJpaDialect();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setJpaDialect(jpd);
factory.setPackagesToScan("org.browsexml.timesheetjob.model");
factory.setDataSource(getTimeSheetDatasource());
factory.afterPropertiesSet();
EntityManagerFactory ret = factory.getObject();
LOGGER.debug("xxx entity manager factory " + ret);
return ret;
}
#Bean
public EntityManager entityManager(#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
LOGGER.debug("xxx entity manager");
EntityManager ret = entityManagerFactory.createEntityManager();
LOGGER.debug("xxx entity manager " + ret);
return ret;
}
#Bean
public PlatformTransactionManager transactionManager() throws SQLException, NamingException {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
In SpringBoot I get the following exception:
2022-01-27 14:18:23,297 ERROR org.springframework.boot.SpringApplication 843 [restartedMain] Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'openEntityManagerInViewInterceptorConfigurer' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration$JpaWebConfiguration.class]: Unsatisfied dependency expressed through method 'openEntityManagerInViewInterceptorConfigurer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openEntityManagerInViewInterceptor' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration$JpaWebConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:720)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338)
at com.ritchey.timesheet.Timesheet.main(Timesheet.java:55)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'openEntityManagerInViewInterceptorConfigurer' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration$JpaWebConfiguration.class]: Unsatisfied dependency expressed through method 'openEntityManagerInViewInterceptorConfigurer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openEntityManagerInViewInterceptor' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration$JpaWebConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1598)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1562)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1451)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1338)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:760)
... 23 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openEntityManagerInViewInterceptor' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration$JpaWebConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
... 39 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.orm.jpa.EntityManagerFactoryUtils.findEntityManagerFactory(EntityManagerFactoryUtils.java:121)
at org.springframework.orm.jpa.EntityManagerFactoryAccessor.setBeanFactory(EntityManagerFactoryAccessor.java:155)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1826)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1791)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
... 49 common frames omitted
Got past this error by setting in application.properties:
spring.jpa.open-in-view=false
Not sure what is going on here.

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 Filter error, Failed to register after unregistered Filter

Im both new to Spring Boot and Kotlin.
I'm having an error saying that
Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException:
Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
2018-10-03 15:50:21.601 ERROR 63436 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
at com.jxinternet.platform.ms.merchant.MerchantApplicationKt.main(MerchantApplication.kt:28)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
... 20 common frames omitted
Caused by: java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.security.config.annotation.web.builders.FilterComparator.registerAfter(FilterComparator.java:156)
at org.springframework.security.config.annotation.web.builders.HttpSecurity.addFilterAfter(HttpSecurity.java:1121)
at com.jxinternet.platform.ms.merchant.config.security.WebSecurityConfig.configure(WebSecurityConfig.kt:64)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:230)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:321)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:92)
at com.jxinternet.platform.ms.merchant.config.security.WebSecurityConfig$$EnhancerBySpringCGLIB$$7e2d609b.init(<generated>)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c.CGLIB$springSecurityFilterChain$3(<generated>)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c$$FastClassBySpringCGLIB$$d83091e8.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c.springSecurityFilterChain(<generated>)
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.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 21 common frames omitted
Disconnected from the target VM, address: '127.0.0.1:51914', transport: 'socket'
Process finished with exit code 1
my ReplaceResponseFilter.kt
package com.jxinternet.platform.ms.merchant.config.security
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.Order
import org.springframework.hateoas.VndErrors
import org.springframework.http.HttpStatus
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.GenericFilterBean
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponseWrapper
open class ReplaceResponseFilter : Filter {
companion object {
private val log = LoggerFactory.getLogger(ReplaceResponseFilter::class.java)
}
override fun doFilter(request: ServletRequest, response: ServletResponse, filterChain: FilterChain) {
val t = response as HttpServletResponseWrapper
}
override fun init(p0: FilterConfig?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun destroy(){
}
}
my WebSecurityConfig.kt
package com.jxinternet.platform.ms.merchant.config.security
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
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.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.firewall.HttpFirewall
import org.springframework.security.web.firewall.StrictHttpFirewall
#Configuration
#EnableWebSecurity
class WebSecurityConfig(
private val tokenAuthenticationService: TokenAuthenticationService,
private val objectMapper: ObjectMapper
) : WebSecurityConfigurerAdapter() {
// 防止防止url带两个// spring security 5会有问题 所以必须放开这个配置
#Bean
fun allowUrlEncodedSlashHttpFirewall(): HttpFirewall {
val firewall = StrictHttpFirewall()
firewall.setAllowUrlEncodedSlash(true)
return firewall
}
override fun configure(web: WebSecurity) {
super.configure(web)
web.httpFirewall(allowUrlEncodedSlashHttpFirewall())
}
// 设置 HTTP 验证规则
override fun configure(http: HttpSecurity) {
// 关闭csrf验证
http.csrf().disable()
// 对请求进行认证
.authorizeRequests()
// 所有 / 的所有请求 都放行
.antMatchers(
"/",
"/pay/**",
"/scan/**",
"/login",
"/actuator/health",
"/webjars/springfox-swagger-ui/**",
"/swagger-ui.html",
"/configuration/ui",
"/swagger-resources",
"/v2/api-docs",
"/swagger-resources/**").permitAll()
// 所有 /login 的POST请求 都放行
// 所有请求需要身份认证
.anyRequest().authenticated()
.and()
// 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容
//.addFilterBefore(loginFilter(objectMapper, tokenAuthenticationService), UsernamePasswordAuthenticationFilter::class.java)
// 添加一个过滤器验证其他请求的Token是否合法
.addFilterBefore(JWTAuthenticationFilter(tokenAuthenticationService, objectMapper), UsernamePasswordAuthenticationFilter::class.java)
.addFilterAfter(ReplaceResponseFilter(), ReplaceResponseFilter::class.java)
// 设置session无状态!!
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}
}
In ReplaceResponseFilter, you're missing:
filterChain.doFilter(request, response)
Otherwise, your filter chain cannot continue.
I also believe that this is incorrect:
.addFilterAfter(ReplaceResponseFilter(), ReplaceResponseFilter::class.java)
As far as I understand your code, that filter should come after JWTAuthenticationFilter. Therefore:
.addFilterAfter(ReplaceResponseFilter(), JWTAuthenticationFilter::class.java)

Using #DataJpaTest when multiple datasources are configured [duplicate]

This question already has answers here:
Using #DataJpaTest with multiple DataSource and custom repository implementation [duplicate]
how to use #DataJpaTest with multiple datasourse
(3 answers)
Closed 4 years ago.
My application is configured with two datasources, following this example: https://github.com/snicoll-demos/demo-multi-entity-managers
Everything works when running the app, but when I try to add a #DataJpaTest, it isn't able to load the application context:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/example/reports/ws/MainDatabaseConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'mainEntityManager' threw exception; nested exception is java.lang.IllegalArgumentException: No visible constructors in class org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
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.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 49 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'mainEntityManager' threw exception; nested exception is java.lang.IllegalArgumentException: No visible constructors in class org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 66 more
Caused by: java.lang.IllegalArgumentException: No visible constructors in class org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean
at org.springframework.cglib.proxy.Enhancer.filterConstructors(Enhancer.java:666)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:567)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:329)
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:337)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.createCglibProxyForFactoryBean(ConfigurationClassEnhancer.java:531)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.enhanceFactoryBean(ConfigurationClassEnhancer.java:502)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:340)
at com.example.reports.ws.MainDatabaseConfig$$EnhancerBySpringCGLIB$$22c681c6.mainDataSource(<generated>)
at com.example.reports.ws.MainDatabaseConfig.mainEntityManager(MainDatabaseConfig.java:59)
at com.example.reports.ws.MainDatabaseConfig$$EnhancerBySpringCGLIB$$22c681c6.CGLIB$mainEntityManager$2(<generated>)
at com.example.reports.ws.MainDatabaseConfig$$EnhancerBySpringCGLIB$$22c681c6$$FastClassBySpringCGLIB$$c8213502.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
at com.example.reports.ws.MainDatabaseConfig$$EnhancerBySpringCGLIB$$22c681c6.mainEntityManager(<generated>)
Anyone know what I need to do to get Spring's magic working in this setup?
The configuration for my main database:
package com.example.reports.ws;
import javax.persistence.EntityManagerFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.example.reports.ws.model.ReportDefinition;
import com.example.reports.ws.repos.ChartPrefsRepository;
import com.example.reports.ws.svc.ChartService;
#Configuration
#EntityScan
#EnableTransactionManagement()
#EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "mainTransactionManager", basePackages = "com.example.reports.ws.repos")
public class MainDatabaseConfig {
#Autowired
private Environment env;
#Autowired(required = false)
private PersistenceUnitManager persistenceUnitManager;
#Bean
#ConfigurationProperties("app.main.jpa")
public JpaProperties mainJpaProperties() {
return new JpaProperties();
}
#Bean
#Primary
#ConfigurationProperties(prefix = "app.main.datasource")
public DataSource mainDataSource() {
return (DataSource) DataSourceBuilder.create().type(DataSource.class).build();
}
#Bean(name = "entityManagerFactory")
#Primary
public LocalContainerEntityManagerFactoryBean mainEntityManager(JpaProperties mainJpaProperties) {
EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(mainJpaProperties);
return builder.dataSource(mainDataSource())
.packages(ReportDefinition.class, ChartPrefsRepository.class, ChartService.class)
.persistenceUnit("mainDs").build();
}
private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties mainJpaProperties) {
JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(mainJpaProperties);
return new EntityManagerFactoryBuilder(jpaVendorAdapter, mainJpaProperties.getProperties(),
this.persistenceUnitManager);
}
private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) {
AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(jpaProperties.isShowSql());
adapter.setDatabase(jpaProperties.getDatabase());
adapter.setDatabasePlatform(jpaProperties.getDatabasePlatform());
adapter.setGenerateDdl(jpaProperties.isGenerateDdl());
return adapter;
}
#Bean
#Primary
public PlatformTransactionManager mainTransactionManager(EntityManagerFactory mainEntityManager) {
return new JpaTransactionManager(mainEntityManager);
}
}

Resources