I have a working Spring Boot Web application. We want to persist the session to the DB so I followed the spring tutorial, found here and I am getting this error at startup:
Caused by: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'sessionRepositoryFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.class]: Unsatisfied dependency expressed through method 'sessionRepositoryFilterRegistration' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'org.springframework.boot.autoconfigure.session.JdbcSessionConfiguration$SpringBootJdbcHttpSessionConfiguration': Unsatisfied dependency expressed through method 'setTransactionManager' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'transactionManager' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'connectionsConfiguration': Unsatisfied dependency expressed through field 'emFactory'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'sessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?
Here is my connectionsConfiguration class:
#Configuration
public class ConnectionsConfiguration implements ApplicationListener<ApplicationReadyEvent> {
#Autowired
DataSource dataSource;
#Autowired
private EntityManagerFactory emFactory;
#Bean
public EntityManager getEntityManager() {
return emFactory.createEntityManager();
}
#Bean
#Scope("prototype")
public LocalSessionFactoryBean sessionFactory() throws ClassNotFoundException {
LocalSessionFactoryBean fact = new LocalSessionFactoryBean();
fact.setAnnotatedPackages("com.xxx.persistence.model");
fact.setPackagesToScan("com.xxx.persistence.model");
fact.setDataSource(dataSource);
return fact;
}
}
How do I get this to work? Do I need to explicitly define the sessionFactory? I was under the impression that spring would handle this behind the scenes.
Related
I am currently using Quartz to store scheduled jobs. While trying to use jobstore of type jdbc to persist scheduled jobs in secondary quartz database I am getting bunch of errors regarding injections, beans.
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwtFilter': Unsatisfied dependency expressed through field 'userRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepo' defined in pl.certificatemanager.CertificateManagerApp.repository.UserRepo defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot create inner bean '(inner bean)#29fa6b65' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#29fa6b65': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'quartzDataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration$JdbcStoreTypeConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.quartz.QuartzDataSourceScriptDatabaseInitializer]: Factory method 'quartzDataSourceScriptDatabaseInitializer' threw exception; nested exception is java.lang.IllegalStateException: Unable to detect database type
Error regarding my repository and #EnableJpaRepositories
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepo' defined in pl.certificatemanager.CertificateManagerApp.repository.UserRepo defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot create inner bean '(inner bean)#29fa6b65' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#29fa6b65': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'quartzDataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration$JdbcStoreTypeConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.quartz.QuartzDataSourceScriptDatabaseInitializer]: Factory method 'quartzDataSourceScriptDatabaseInitializer' threw exception; nested exception is java.lang.IllegalStateException: Unable to detect database type
Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#29fa6b65': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'quartzDataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration$JdbcStoreTypeConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.quartz.QuartzDataSourceScriptDatabaseInitializer]: Factory method 'quartzDataSourceScriptDatabaseInitializer' threw exception; nested exception is java.lang.IllegalStateException: Unable to detect database type
And last one concerning Quartz DataSource directly. However I think resolving problems with primary DataSource first is priority for now.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'quartzDataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration$JdbcStoreTypeConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.quartz.QuartzDataSourceScriptDatabaseInitializer]: Factory method 'quartzDataSourceScriptDatabaseInitializer' threw exception; nested exception is java.lang.IllegalStateException: Unable to detect database type
application.properties
## Primary DataSource properties
database1.datasource.url=jdbc:mysql://localhost:3306/certificatemanagerdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.configuration.maximum-pool-size=30
database1.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
## Quartz properties
spring.quartz.job-store-type=jdbc
spring.quartz.properties.org.quartz.threadPool.threadCount=5
spring.quartz.jdbc.initialize-schema=always
database2.datasource.url=jdbc:mysql://localhost:3306/quartz_schema
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
DataSourcesConfiguration
#Configuration
#EnableAutoConfiguration
public class DataSourcesConfiguration {
#Bean
#Primary
#ConfigurationProperties("database1.datasource")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#Primary
#ConfigurationProperties("database1.datasource.first.configuration")
public HikariDataSource firstDataSource(DataSourceProperties firstDataSourceProperties) {
return firstDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
#Bean
#QuartzDataSource
#ConfigurationProperties(prefix = "database2.datasource")
public DataSource quartzDataSource() {
return DataSourceBuilder.create().build();
}
}
SecurityConfig it injects jwtFilter mentioned in error
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private CustomPasswordEncoder customPasswordEncoder;
#Autowired
private JwtFilter jwtFilter;
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(customPasswordEncoder.getPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http = http.csrf().disable().cors().disable();
http = http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and();
http = http.exceptionHandling()
.authenticationEntryPoint((request, response, exception) -> {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
}).and();
http.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}
}
userRepo
#Repository
public interface UserRepo extends JpaRepository<User, Long> {
User findUserById(Long id);
User findByUsername(String username);
Boolean existsByUsername(String username);
}
When commenting out method quartzDataSource() in DataSourcesConfiguration everything works fine (ignoring persisting data of Quartz Scheduler), so I suspect something with configuring Quartz DataSource intervene with my whole app.
Injected class JwtUtil in SecurityConfig is annotated with #Component.
Found the solution. Replaced spring.datasource.url= with spring.datasource.jdbcUrl= and everything works fine.
#Autowired
private Configuration freemarkerConfig;
Getting the following exception,
Unsatisfied dependency expressed through field 'freemarkerConfig';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'freeMarkerConfiguration' defined in class path resource [org/springframework/boot/autoconfigure/freemarker/FreeMarkerServletWebConfiguration.class]: Unsatisfied dependency expressed through method 'freeMarkerConfiguration' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'freeMarkerConfigurer' defined in class path resource [org/springframework/boot/autoconfigure/freemarker/FreeMarkerServletWebConfiguration.class]: Invocation of init method failed;
nested exception is freemarker.core.Configurable$UnknownSettingException: Unknown FreeMarker configuration setting: "recognize_standard_file_extensions"
I had the same issue, make sure you are autowiring correct FreeMarker Configuration, or use
#Autowired
private freemarker.template.Configuration freeMarker;
I have a big problem.
I have an application with Spring-Boot and Spring-Data.
It goes well before that i moved some classes and refactory the directory.
I have two database and before i moved classes, i had this config class for a second database:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
basePackages="it.phoops.rt.grigliaprocessi.util",
entityManagerFactoryRef = "organoEntityManager",
transactionManagerRef = "organoTransactionManager")
public class OrganoConfig {
#Bean(name = "organoDataSource")
#ConfigurationProperties(prefix="organo.datasource")
public DataSource organoDataSource(){
return DataSourceBuilder.create().build();
}
#Bean(name="organoEntityManager")
public LocalContainerEntityManagerFactoryBean
organoEntityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("organoDataSource") DataSource dataSource){
return
builder.
dataSource(organoDataSource()).
packages("it.phoops.rt.grigliaprocessi.util.entity").
persistenceUnit("organo").build();
}
#Bean("organoTransactionManager")
public PlatformTransactionManager
organoTransactionManager()
{
return new
DataSourceTransactionManager(organoDataSource());
}
}
Now, i moved in "it.phoops.rt.grigliaprocessi.organo" and i change the value of "basePackages" from "it.phoops.rt.grigliaprocessi.util" to "it.phoops.rt.grigliaprocessi.organo" and
the string "it.phoops.rt.grigliaprocessi.util.entity" to it.phoops.rt.grigliaprocessi.organo.entity".
I moved Entity, Service and Repository classes from:
it.phoops.rt.grigliaprocessi.util.controller
it.phoops.rt.grigliaprocessi.util.entity
it.phoops.rt.grigliaprocessi.util.repository
to
it.phoops.rt.grigliaprocessi.organo.controller
it.phoops.rt.grigliaprocessi.organo.entity
it.phoops.rt.grigliaprocessi.organo.repository
But now, i have this error, caused of nested exception:
Caused by: java.lang.IllegalArgumentException: Not a managed type:
class it.phoops.rt.grigliaprocessi.organo.entity.Albero
......
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'alberoRepository': Invocation of init
method failed; nested exception is
java.lang.IllegalArgumentException:
Not a managed type: class
it.phoops.rt.grigliaprocessi.organo.entity.Albero
....
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error
creating bean with name 'alberoService': Unsatisfied dependency
expressed through field 'repo'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating
bean with name 'alberoRepository': Invocation of init method failed;
nested exception is java.lang.IllegalArgumentException: Not a managed
type: class it.phoops.rt.grigliaprocessi.organo.entity.Albero
....
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error
creating bean with name 'alberoController': Unsatisfied dependency
expressed through field 'alberoService'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error
creating bean with name 'alberoService': Unsatisfied dependency
expressed through field 'repo'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating
bean with name 'alberoRepository': Invocation of init method failed;
nested exception is java.lang.IllegalArgumentException: Not a managed
type: class it.phoops.rt.grigliaprocessi.organo.entity.Albero
Can you help me ?
Thanks
Change you basepackages declaration from it.phoops.rt.grigliaprocessi.util to it.phoops.rt.grigliaprocessi.organo. Also please check the basepackages in componentScan in your Spring boot main class.
I have one UserRepository which is a CRUD repository as shown:
#Repository
public interface UserRepository extends CrudRepository<User, Long> {
}
one UserController like this:
#RestController
#RequestMapping("/api")
public class UserController {
#Autowired
private UserRepository repository;
#Autowired
private UserResourceAssembler assembler;
and one WebMvcTest class to test my UserController:
#RunWith(SpringRunner.class)
#WebMvcTest(UserController.class)
public class UserControllerTest {
#Autowired
private MockMvc mvc;
#Test
public void getAllEmployeesAPI() throws Exception
{
mvc.perform( MockMvcRequestBuilders
.get("/api/users")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
}
When I run the server everything is fine. However I get this error when I run maven-test:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userController': Unsatisfied dependency
expressed through field 'repository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'userRepository': Cannot create inner bean
'(inner bean)#7ba1cdbe' of type
[org.springframework.orm.jpa.SharedEntityManagerCreator] while setting
bean property 'entityManager'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name '(inner bean)#7ba1cdbe': Cannot resolve
reference to bean 'entityManagerFactory' while setting constructor
argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'entityManagerFactory' available Caused by:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'userRepository': Cannot create inner bean
'(inner bean)#7ba1cdbe' of type
[org.springframework.orm.jpa.SharedEntityManagerCreator] while setting
bean property 'entityManager'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name '(inner bean)#7ba1cdbe': Cannot resolve
reference to bean 'entityManagerFactory' while setting constructor
argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'entityManagerFactory' available Caused by:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name '(inner bean)#7ba1cdbe': Cannot resolve
reference to bean 'entityManagerFactory' while setting constructor
argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'entityManagerFactory' available Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'entityManagerFactory' available
If you have the same structure now, i recommend #SpringBootTest.
#WebMvcTest does not load database-related beans into the application context.
#WebMvcTest loads just the Web layer. If it contains some dependencies, you need to load your application context as well. You could narrow the dependencies used only in your controller with the #ContextConfiguration(classes = {YouTestConfiguration.class})
We're trying to implement AspectJ #Aspect into our existing software for executing some code after a service call is made.
Note:
We have service interfaces and implementations being #Autowired
throughout the project via rest controllers as well as other service implementations.
This project is entirely a Java Configuration with no XML whatsoever.
We're using Spring 4.1.2 RELEASE deployed on Tomcat 7.0.54.
Issue:
When we added #EnableAspectJAutoProxy into our main #JavaConfig, we experience the following exception:
Unresolvable circular reference.
Which fails every #Autowired attempt on a long list of beans.
Tried:
Removed the #EnableAspectJAutoProxy annotation which autowires everything correctly but our #Aspect never gets invoked.
Added the CGLIB support in the annotation by declaring
proxytargetclass=true to no avail.
We've tried following this documentation directly from Spring: #EnableAspectJAutoProxy Javadoc
This seems to be an issue with AspectJ's proxy mechanism dealing with autowired dependencies.
Why does this occur when we add the #EnableAspectJAutoProxy?
Our Java Config:
#Configuration
#EnableWebMvc
#EnableJpaRepositories(basePackages ={"com.company.product.persistence.repository"})
#EnableTransactionManagement
#EnableSwagger
#EnableAspectJAutoProxy
#PropertySource({"classpath:hibernate.properties",
"classpath:auth.properties",
"classpath:mail.properties",
"classpath:locations.properties"
})
#ComponentScan(basePackages = {"com.company.product"})
public class WebConfig extends WebMvcConfigurerAdapter {
//Bean declarations here.
//Note: All services/repos/controllers are annotation based.
}
Aspect implementation:
#Aspect
#Component
public class PostMessageAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#After("execution(*com.company.product.persistence.serviceImpl.event.eventServiceImpl.methodCall(..))")
public void postMessageRun(final JoinPoint joinPoint) {
logger.info("CALLED AFTER METHOD");
}
}
Update:
Managed to get AOP/AspectJ working perfectly fine on one dev machine only requiring a minor change to our Spring Security config. We are both using Intellij, openJDK 1.7.0_65 on Ubuntu 14.0.4 running on default instances of Tomcat 7.0.56. On the other machine running the same software stack, gets the following.
Stack Trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dispatchingMessageController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.event.DispatchingEventService com.apx.efm.controllers.message.DispatchingMessageController.dispatchingEventService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dispatchingEventServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingAd dressesService com.apx.efm.persistence.serviceImpl.event.DispatchingEventServiceImpl.buildingAddressesService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingAddressServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingService com.apx.efm.persistence.serviceImpl.building.BuildingAddressServiceImpl.buildingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingAddressesService com.apx.efm.persistence.serviceImpl.building.BuildingServiceImpl.buildingAddressesService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.aopalliance.intercept.MethodInterceptor]: Factory method 'methodSecurityInterceptor' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.apx.efm.persistence.service.user.EfmUserService com.apx.efm.application.config.SecurityConfig.efmUserService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'efmUserServiceImpl' defined in file [/home/apxdev4/Development/GitRepositories/efim-restful-web-service/target/EFIM/WEB-INF/classes/com/apx/efm/persistence/serviceImpl/user/EfmUserServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'methodSecurityInterceptor': Requested bean is currently in creation: Is there an unresolvable circular reference?
This was entirely an issue with our Spring configuration. Our Spring Security configuration was trying to #Autowired beans while they were still in the middle of being processed by our main application configuration. We solved this by ensuring that Spring Security gets configured after the main #Configuration.
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
// Initialize web mvc
appContext.setDisplayName("APP");
appContext.register(WebConfig.class);
appContext.register(SecurityConfig.class);
// Rest omitted (listeners, dispatcher servlet, etc.)
}