I have a central library for certain functions and now I have trouble integrating that library.
The library is written in spring boot and contains a class: com.common.Security.
It is defined like this:
package com.common;
....
#Service
#EnableConfigurationProperties(SecurityProperties.class)
#Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Security {
....
}
I try to use this in another class:
package org.special;
import com.common.Security;
#Configuration
public class WebServiceConfig {
#Autowired
private Security security;
....
}
But I get some errors:
Error creating bean with name 'myController': Unsatisfied dependency expressed through field 'WebServiceclient';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'webserviceClient':
Unsatisfied dependency expressed through field 'template'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'webServiceTemplate' defined in class path resource [org/special/WebServiceConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.ws.client.core.WebServiceTemplate]: Factory method 'webServiceTemplate' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
nested exception is org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.Security': Scope 'request' is not active for the current thread;
consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found:
What can I do to fix this?
Removing the Scope was quite helpfull.
I tried this before but some of my tests failed after that. I didn't see, that this was because of missing settings in application.yaml for the tests.
They were not neccessary when scope is request.
Related
When upgrading my application from Spring Boot 2.5 to 2.6, I am getting this error :
Error creating bean with name 'securityConfig': Unsatisfied dependency
expressed through method 'setContentNegotationStrategy' parameter 0;
nested exception is
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 'org.springdoc.ui.SwaggerConfig':
Unsatisfied dependency expressed through field
'swaggerIndexTransformer';
nested exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'org.springdoc.ui.SwaggerConfig':
Requested bean is currently in creation: Is there an unresolvable
circular reference?
This error is documented on https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.6-Release-Notes#circular-references-prohibited-by-default and I know I could "fix" it by setting a property and go back to Spring Boot 2.5 behavior.. But if I can take the opportunity to fix a circular reference, I may as well do it for the future.
My securityConfig is simple, because my application is a public application returning some html content, to all callers, with no authentication. so this is my config :
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity security) throws Exception {
//application is open to everyone - no security
security.httpBasic().disable();
}
}
the setContentNegotationStrategy that the error mentions is a method from WebSecurityConfigurerAdapter that I am not overriding, so I am not able to understand what I need to do.
if I delete my SecurityConfig class, then I still have an error, same as before but without the mention of my SecurityConfig class:
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 'org.springdoc.ui.SwaggerConfig':
Unsatisfied dependency expressed through field
'swaggerIndexTransformer';
nested exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'org.springdoc.ui.SwaggerConfig':
Requested bean is currently in creation: Is there an unresolvable
circular reference?
what is the recommended way to deal with what seems to be a circular reference between Spring Security and org.springdoc.ui.SwaggerConfig ?
The problem's caused by org.springdoc.ui.SwaggerConfig. It has been fixed by these changes which are available in springdocs-openapi 1.5.13.
I want to implement JPA repositories as mentioned here. I think my problem is I want to use some functions from the JPA Repository itself and I #Autorwired it But I'm not completely sure
Error Message:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addBothStudentsHandler': Unsatisfied dependency expressed through method 'setMajorRepository' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'majorRepository' defined in io.asiam.tansiq.repositories.MajorRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot create inner bean '(inner bean)#78f146b5' of type [org.springframework.data.repository.core.support.RepositoryFragmentsFactoryBean] while setting bean property 'repositoryFragments'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#78f146b5': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customMajorRepositoryImplFragment': Cannot resolve reference to bean 'customMajorRepositoryImpl' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customMajorRepositoryImpl': Unsatisfied dependency expressed through field 'majorRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'majorRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
What I have tried so far:
1- tried to use setter-based #Autowired instead of field-based (But no change)
2- tried to use #Lazy also nothing changed
**Code: **
CustomMajorRepository.java
public interface CustomMajorRepository {
void addStudentToMajor(Student student, Major major);
void increaseMajorLimit(UUID majorId, int amount);
}
CustomMajorRepositoryImpl.java
private MajorRepository majorRepository;
public MajorRepository getMajorRepository() {
return majorRepository;
}
#Autowired
public void setMajorRepository(MajorRepository majorRepository) {
this.majorRepository = majorRepository;
}
// rest of implementation details
MajorRepository.java
#Lazy
public interface MajorRepository extends JpaRepository<Major, UUID>, CustomMajorRepository {
}
I think you should use dependency injection via constructor or setter, for example:
private MajorRepository majorRepository;
public CostumMajorRepositoryImpl(MajorRepository mh) {
this.majorRepository = mh;
}
Here is the spring.io article about the setter and constructor injection:
https://spring.io/blog/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/
I tried to expose my Spring Restful web api to Pivotal Cloud Foundary, I successfully connected with Pivotal MySql database, in Local it is working fine but when I push the war in PCF it throws an exception
nested exception is java.lang.IllegalStateException: #Bean method
SpringBeanContainer.dataSource called as bean reference for type
[org.apache.commons.dbcp2.BasicDataSource] but overridden by non-compatible
bean instance of type [org.cloudfoundry.reconfiguration.org.springframework.cloud.service.relational.UrlDecodingDataSource].
I am new to cloud and i don't have an idea much about it, it seems that UrlDecodingDataSource tries to override something, due to this my sessionFactory is not able to create as bean.
Detailed Log
[OUT] org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'loginController': Unsatisfied dependency
expressed through field 'userDetailService'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userDetailService': Unsatisfied dependency
expressed through field 'uddDao'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'userDetailDaoImpl': Unsatisfied dependency expressed
through field 'sessionFactory'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'sessionFactory' defined in
com.javarnd.cc.configuration.SpringBeanContainer: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method
'sessionFactory' threw exception; nested exception is
java.lang.IllegalStateException: #Bean method SpringBeanContainer.dataSource
called as bean reference for type [org.apache.commons.dbcp2.BasicDataSource]
but overridden by non-compatible bean instance of type [org.cloudfoundry.reconfiguration.org.springframework.cloud.service.relational.UrlDecodingDataSource].
DataSource snippet in my SpringBeanContainer
#Bean // Simple Bean Defination in XML
public BasicDataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty(DRIVER_CLASS));
dataSource.setUrl(env.getProperty(URL));
dataSource.setUsername(env.getProperty(USERNAME));
dataSource.setPassword(env.getProperty(PASSWORD));
return dataSource;
}
Kindly help me to resolve this or sugge
when starting the application, see the below error:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blockDataController': Injection of resource dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blockSummaryImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'prodCodeMapper' defined in file [D:\YueNiuProject\StockMarket\yueniu-stock-data\market-data-dao\target\classes\com\yueniu\stock\market\data\mapper\block\ProdCodeMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception;
nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
the connection with a sql database, you must configure datasource in application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://..
spring.datasource.username=//..
spring.datasource.password=//..
if you dont need to config the datasource, you can use the exclude . like this:
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
it would not register the DataSource with default configuration, then passed the issue for throw Exception
sometimes if you bean configuration in same package it won't work. Like the properties loading bean need to be in separate package. Not sure this answer will be accepted or not , for me it worked after moving below code into different package.
#Bean
public PlatformTransactionManager oracleTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(oracleEntityManager().getObject());
return transactionManager;
}
I have an existing Java app using Spring MVC 3.2.1. The existing unit tests all work fine. Now I'm trying to a new unit test, using the #WebAppConfiguration annotation for the first time, and it's blowing up with a wacky error.
Here's my new unit test, taken almost verbatim from this page:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations={"classpath:war-test-context.xml"})
#Transactional
public class GenericPageControllerTest {
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = webAppContextSetup(this.webApplicationContext).build();
}
#Test
public void testControllerSecurityTestThingyTestWithALongNameTest() throws Exception {
this.mockMvc.perform(get("/payOptions.html"))
.andExpect(redirectedUrl("/login.html"));
}
}
Here's the error I'm getting:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in class path resource [war-test-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [war-test-context.xml]: Cannot resolve reference to bean 'persistenceUnitManager' while setting bean property 'persistenceUnitManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceUnitManager' defined in class path resource [war-test-context.xml]: Cannot resolve reference to bean 'caDataSource' while setting bean property 'dataSources' with key [TypedStringValue: value [caDataSource], target type [null]]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caDataSource': Invocation of init method failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: Failed to populate database; nested exception is org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from ServletContext resource [/database/myapp_schema.sql]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [war-test-context.xml]: Cannot resolve reference to bean 'persistenceUnitManager' while setting bean property 'persistenceUnitManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceUnitManager' defined in class path resource [war-test-context.xml]: Cannot resolve reference to bean 'caDataSource' while setting bean property 'dataSources' with key [TypedStringValue: value [caDataSource], target type [null]]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caDataSource': Invocation of init method failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: Failed to populate database; nested exception is org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from ServletContext resource [/database/myapp_schema.sql]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceUnitManager' defined in class path resource [war-test-context.xml]: Cannot resolve reference to bean 'caDataSource' while setting bean property 'dataSources' with key [TypedStringValue: value [caDataSource], target type [null]]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caDataSource': Invocation of init method failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: Failed to populate database; nested exception is org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from ServletContext resource [/database/myapp_schema.sql]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caDataSource': Invocation of init method failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: Failed to populate database; nested exception is org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from ServletContext resource [/database/myapp_schema.sql]
Caused by: org.springframework.dao.DataAccessResourceFailureException: Failed to populate database; nested exception is org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from ServletContext resource [/database/myapp_schema.sql]
Caused by: org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from ServletContext resource [/database/myapp_schema.sql]
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/database/myapp_schema.sql]
Other tests using just the #ContextConfiguration annotation find this file and instantiate this bean just fine. Can anyone tell me why the #WebAppConfiguration bean is making it throw up? Here's the configuration section it's telling me won't work:
<jdbc:embedded-database id="caDataSource" type="HSQL">
<jdbc:script location="database/myapp_schema.sql"/>
<jdbc:script location="database/myapp_data.sql"/>
</jdbc:embedded-database>
The files are on the classpath, but they're in a different project - that might be the only wrinkle. Anyone got any ideas, or handy links?
Looks like this is the reason.
When you use WebApplicationContext you lose the ability to use classpath: configuration or other stuff, and are limited to whatever's in /src/main/webapp (or another location as provided).
WebAppContext javadoc is here.