I'm trying to test my application following samples on the Spring website.
These are my dependencies:
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile("org.springframework.boot:spring-boot-starter-security")
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity4")
runtime('org.springframework.boot:spring-boot-devtools')
runtime('com.h2database:h2')
runtime('mysql:mysql-connector-java')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.springframework.security:spring-security-test')
}
And this is the test class:
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class ProductControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void testHomePage() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk());
}
}
I get the error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
java.lang.IllegalStateException: Failed to load ApplicationContext
Any idea what may be causing this? I don't have any specific configuration files, only the a security configuration and a webconfig.
Webconfig:
public class WebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**", "/css/**", "/fragments/**")
.addResourceLocations("classpath:/static/images/", "classpath:/static/css/", "classpath:/fragments/");
}
}
The following line in the output:
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
Tells us that the class javax.xml.bind.JAXBException is not found.
As #Antot mentionned, adding the following dependency to your graddle should fix the issue:
compile('javax.xml.bind:jaxb-api:2.3.0')
For those using Maven, use the following:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
Related
After updating to Spring Boot 2.6.8 with Java v11 and using Junit5 I'm not able to Mock anymore MongoTemplate
#ExtendWith(SpringExtension.class)
#ContextConfiguration(classes={RepositoryImpl.class})
class RepositoryImplTest {
#Autowired
private RepositoryImpl repositoryImpl;
#MockBean
private MongoTemplate db;
...
}
I get the following error
java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.mockito.exceptions.base.MockitoException: Mockito cannot mock this class: class org.springframework.data.mongodb.core.MongoTemplate.
as per dependency I have in pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
I am trying to implement oauth2 on some endpoints within my API. here is my config class:
#Configuration
#Order(102)
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers(HttpMethod.GET, "/").permitAll()
.mvcMatchers(HttpMethod.GET, "/endpoint1").hasAuthority("SCOPE_READ")
.mvcMatchers(HttpMethod.GET, "/").hasAuthority("SCOPE_WRITE")
.anyRequest().authenticated()
.and()
.oauth2ResourceServer().jwt();
}
There are other config files within my project hence I added the order annotation but I keep receiving the Error creating bean with name 'springSecurityFilterChain error.
Here are the related dependencies in my pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>com.okta.spring</groupId>
<artifactId>okta-spring-boot-starter</artifactId>
<version>1.5.1</version>
</dependency>
I tried explicitly using the last version (5.5.3) of spring security web but I'm still receiving the error. Here's the full stack trace:
"timestamp":"2021-11-02T15:16:59.774Z","message":"Application run failed","logger":"o.s.b.SpringApplication","thread":"restartedMain","level":"ERROR","stack_trace":"<#20be4d11> o.s.b.f.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.NoClassDefFoundError: org/springframework/core/log/LogMessage\r\n\tat o.s.b.f.s.ConstructorResolver.instantiate(ConstructorResolver.java:627)\r\n\tat o.s.b.f.s.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456)\r\n\tat o.s.b.f.s.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)\r\n\tat o.s.b.f.s.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
This is my first time working with the Spring security features and would like more insight on resolving this issue.
My spring boot test is throwing the below error during maven build.
"level":"ERROR","logger":"com.zaxxer.hikari.HikariConfig","msg":"HikariPool-1 - jdbcUrl is required with driverClassName."
Stacktrace:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schedulerFactoryBean' defined in class path resource
[com/pit/SchedulerConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: jdbcUrl is requir
ed with driverClassName.
Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
The method that throws an error in my MyApplicationTest.java
#SpringBootTest
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableConfigurationProperties(value = MyConfig.class)
class MyApplicationTest {
#Test
void contextLoads() {
assertNotNull(myController);
}
}
My pom has these dependencies in classpath.
spring-boot-starter-web
spring-boot-starter-test
spring-integration-sftp
postgresql
junit
quartz-scheduler
My Datasource bean is configured as below
#Configuration
public class MyDataSourceCfg {
private DataSource appDataSource() {
return DataSourceBuilder.create()
.driverClassName("org.postgresql.Driver")
.url(env.getProperty("url") // values are set from Environment
.username(env.getProperty("user"))
.password(env.getProperty("password")
.build();
}
}
Please tell me what is happening and how I avoid this error. I read about configuring Datasource in different way in case you have multiple database but I just have one postgres database. Please share your thoughts.
Considering that you have all relevant dependencies.
as Connect to PostgreSQL Database with Spring Data JPA such as :-
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
and in application.properties file:
spring.datasource.url=jdbc:postgresql://localhost:5432/dev
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
With SpringBoot's powerful autoconfiguration, you don't need to explicitly create a DataSource bean and if in case you want, use these properties values.
While trying to follow the article https://sandor-nemeth.github.io/java/spring/2017/06/15/spring-boot-with-keycloak.html
I set up my keycloak oauth in spring boot application exactly the same apart form the fact that I am using maven pom.xml instead of gradle.
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-2-starter</artifactId>
<version>4.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-adapter</artifactId>
<version>9.0.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>9.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
The Java part is the same as in the article:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class KeycloakSecurityConfigurer extends KeycloakWebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth) {
final SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
mapper.setConvertToUpperCase(true);
final KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider();
provider.setGrantedAuthoritiesMapper(mapper);
auth.authenticationProvider(provider);
}
#Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
#Override
protected void configure(final HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests();
}
While trying to start the spring boot application
java ${JAVA_OPTS} -Djava.security.egd=file:/dev/./urandom -jar "${HOME}/app.war" "$#"
I am getting BeanInCreationException:
rg.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.keycloak.adapters.springboot.KeycloakAutoConfiguration': Unsatisfied dependency expressed through method 'setKeycloakSpringBootProperties' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'keycloakSecurityConfigurer': Unsatisfied dependency expressed through field 'keycloakConfigResolver'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'keycloakConfigResolver': Requested bean is currently in creation: Is there an unresolvable circular reference?","logger":"org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext","thread":"main","level":"WARN"}
{"time":"2020-03-10T12:53:22.667+00:00","msg":"Application run failed","logger":"org.springframework.boot.SpringApplication","thread":"main","level":"ERROR","stack_trace":"org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.keycloak.adapters.springboot.KeycloakAutoConfiguration': Unsatisfied dependency expressed through method 'setKeycloakSpringBootProperties' parameter 1
I have a spring boot application with the following configuration:
Application
#SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class,
DataSourceAutoConfiguration.class,JpaRepositoriesAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {
Main configuration class:
#Configuration
#ComponentScan("com.mycompany.it")
#Import(DatabaseConfiguration.class)
public class Configuration extends WebMvcConfigurationSupport {
Database configuration:
#Configuration
#ComponentScan(basePackages = {"com.mycompany.it.xp2.integration.workday.dao","com.mycompany.it.xp2.integration.workday.application","com.company.it.xp2.integration.workday.model"})
#EnableAspectJAutoProxy
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"com.company.it.xp2.integration.workday.dao","com.company.it.xp2.integration.workday.model"})
public class DatabaseConfiguration {
With DataSource bean declaration:
#Bean(destroyMethod = "close")
#Primary
public DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource source = new ComboPooledDataSource();
source.setDriverClass(driverClass);
source.setJdbcUrl(jdbcUrl);
source.setUser(jdbcUsername);
source.setPassword(jdbcPassword);
source.setInitialPoolSize(initialSize);
source.setMaxPoolSize(maxActive);
source.setMinPoolSize(minIdle);
return source;
}
However when I start up the application I get the following error:
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration':
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'javax.sql.DataSource' available: expected at
least 1 bean which qualifies as autowire candidate. Dependency
annotations: {}
Here are the related lines from gradle:
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop'
compile group: 'org.springframework', name: 'spring-orm'
compile group: "org.springframework.boot", name: "spring-boot-starter-jdbc"
compile "org.springframework.boot:spring-boot-starter-data-jpa"
Spring boot version 1.5.3
Check the error log
1 bean which qualifies as autowire candidate. Dependency annotations
It seems that there is an error when you configured the bean.