Moved config, entity and other classes - java

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.

Related

UnsatisfiedDependencyException when trying to connect with Quartz DataSource

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.

using of freemarker template error occurs configuration failed

#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;

Spring Boot Test cannot resolve repository dependency

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

ContextRefresher in spring autowired

I have a java application in which one of the classes has ContextRefresher autowired:
public abstract class AbstractConfigurationPersister implements IConfigurationPersister {
#Autowired
private ContextRefresher contextRefresher;
#Override
public void forceRefresh() {
contextRefresher.refresh();
}
}
This autowired bean is giving me problems as from the logs, it says that paramater 1 has an unsatisfied dependency.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration$DataSourceTransactionManagerConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'application':
Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'ktc.tanalytics.prediction.PredictionBeanConfiguration':
Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'configurationService' defined in ktc.tanalytics.commons.CommonsBeanConfiguration:
Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'zookeeperConfigurationPersister' defined in ktc.tanalytics.commons.CommonsBeanConfiguration:
Initialization of bean failed; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'contextRefresher' defined in class path resource [org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.class]:
Unsatisfied dependency expressed through method 'contextRefresher' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'refreshScope':
Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor'
defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]:
Factory method 'transactionAdvisor' threw exception; nested exception is java.lang.NullPointerException
Now, I have checked the code of ContextRefresher in spring (https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java) and it receives two arguments.
I suppose that Spring is responsible of creating this ContextRefresher object since it is basically #Autowired. However I do not know why parameter 1 is missing as the log says
Factory method 'transactionAdvisor' threw exception; nested exception is java.lang.NullPointerException
As I focus on the above nested exception, probably transactionAdvisor
is a factory method which tries to create something and while
creating, it is performing some operation on null object.
Just inspect or debug the method: transactionAdvisor , in your code.

Spring Boot 2.0.3 JDBC session persistance error

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.

Categories