I'm trying to test the findByPhoneNumber method in this repository
public interface UserRepository extends ReactiveMongoRepository<User, String> {
Mono<User> findByPhoneNumber(String phoneNumber);
}
ATM, my test looks like this
#ExtendWith(SpringExtension.class)
class UserRepositoryTest {
#Autowired
private UserRepository repository;
#Test
void findByPhoneNumber() {
val phoneNumber = "11111 111111";
val user = repository.save(User.builder().phoneNumber(phoneNumber).password("password").build());
assertEquals(user, repository.findByPhoneNumber(phoneNumber));
}
}
When I run it, I get this error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'io.freesale.repository.UserRepositoryTest': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.freesale.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I'm a Spring noob so please don’t bully me too hard 😀
I was missing the #DataMongoTest annotation
Related
main Class:
package *.*.*;
#SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
DBUtils.java
package *.*.*.dataaccess.dbutils;
#Service
public class DBUtils {
#Autowired
UserRepository userRepository;
public UserEntity getUserEntityById(String id) {
return userRepository.findById(id);
}
}
Repository Class:
package *.*.*.dataaccess.repository;
#Repository
public interface UserRepository extends JpaRepository<UserEntity, UserIdentity> {
UserEntity findById(String id);
}
and also UserEntity java class is in package *.*.*.dataaccess.dao;
Test Class:
#SpringBootTest
class UserApplicationTests {
#Autowired
DBUtils utils; // issue is with this
#Test
void contextLoads() {
}
}
While doing maven test for entire project and getting the below error:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'DBUtils': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '...dataaccess.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '...dataaccess.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I have used #Service on DBUtils and #Repository on JpaRepository but still getting the above error and using springboot is 2.4.1.
Can anyone please help here?
Error creating bean with name 'centralPagamentoPfController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'centralPagamentoPfImpl': Unsatisfied dependency expressed through field 'simulaPagamentoEntryDTO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.itau.internet.mobile.pagamento.model.dto.PagamentoPfSimulacaoRequest' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
#RestController
#RequestMapping("/central_pagamentos")
public class CentralPagamentoPfController extends SummerControllerBase{
#Autowired
private CentralPagamentoPfService service;
//-------PAGAMENTO------------//
#PostMapping(value = "/pagamento/simular")
public Protocol simularPagamentoPf(#RequestBody EntryProtocol entryProtocol){
return service.simularPagamento(entryProtocol, ACTION_SIMULAR_PAGAMENTO, OPKEY_SIMULAR_PAGAMENTO);
}
...................................
public interface CentralPagamentoPfService {
Protocol simularPagamento(final EntryProtocol entryProtocol, String action, String opkey);
}
.......................................
#Service
public class CentralPagamentoPfImpl implements CentralPagamentoPfService, EstatisticaFactory {
#Autowired
private PagamentoPfSimulacaoRequest simulaPagamentoEntryDTO;
#Override
public Protocol simularPagamento(EntryProtocol entryProtocol, String action, String opkey){
PagamentoPfSimulacaoRequest entity = entryProtocol.getBodyAs(PagamentoPfSimulacaoRequest.class);
//code
}
}
........................
public class PagamentoPfSimulacaoRequest implements Serializable{
#JsonProperty("canal_pagamento")
private CanalPagamentoDto canalPagamento;
#JsonProperty("codigo_terminal")
private String codigoTerminal;
// geter e setter
}
below code is working fine but if i comment the jdbcTemplateRandomName method in OracleConfiguration class i get the below error : -
I am trying to understand why i am getting the error by commenting jdbcTemplateRandomName method
Error is in BaseDaoImpl class.
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'baseDaoImpl': Unsatisfied dependency
expressed through field 'jdbcTemplate'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
#Component
public class BaseDaoImpl {
#Autowired
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
#Configuration
public class OracleConfiguration {
#Bean
DataSource dataSource() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
//removed code for brevity setting username,password to datasource
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplateRandomName(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setResultsMapCaseInsensitive(true);
return jdbcTemplate;
}
public class RolesDaoImpl extends BaseDaoImpl implements RolesDao {
//removed lot of unnecessary code for the question
List<Roles> rolesList = getJdbcTemplate().query(sql,
new BeanPropertyRowMapper<Roles>(Roles.class));
If you comment jdbcTemplateRandomName() method you will remove declaration of JdbcTemplate bean from your Spring IoC configuration. So Spring will not be able to find suitable object to populate jdbcTemplate property of your BaseDaoImpl class
I have a simple spring app with one controller
#RestController
public class UserController {
// #Autowired
// UserServiceImpl userService;
#RequestMapping(value="/getUser", method = RequestMethod.GET)
public String getUser(){
// return userService.greetUser();
return "Hello user";
}
It works when I start it. If I uncomment #Autowired and run with the first return statement using UserService it also works.
My Service interface
#Service
public interface UserService {
String greetUser();
void insertUsers(List<User> users);
}
and implementation
#Service
public class UserServiceImpl implements UserService{
#Override
public String greetUser() {
return "Hello user";
}
}
But when I test it, the app falls with the following errors
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 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
The test class
#RunWith(SpringRunner.class)
#WebMvcTest
public class DemoApplicationTests {
#Autowired
private MockMvc mockMvc;
#Test
public void shouldReturnHelloString() throws Exception{
this.mockMvc
.perform(get("/getUser"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("Hello user"));
}
}
Also, if I remove
// #Autowired
// UserServiceImpl userService;
and run test with second return statement, the test execute without error. I understand that the problem is in the UserServiceImpl, but I don't know what it is. What do I need to correct?
You should try to autowire your bean by an interface, not implementation
#Autowired
UserService userService;
And also you should remove #Service from UserService interface
#Configuration
public class MyConfig {
#Bean
public Foobar foobar(#Value("${my.value}") String v) {
return new Foobar(v);
}
}
#Component
public class MyComp {
private final Foobar foobar;
public MyComp(Foobar foobar) {
this.foobar = foobar;
System.out.println(foobar);
}
}
If my.value is not set, I will get this error message
java.lang.IllegalArgumentException: Could not resolve placeholder 'my.value' in string value "${my.value}"
Now my.value is also secured by #ConditionalOnProperty("my.value")
#Configuration
public class MyConfig {
#ConditionalOnProperty("my.value")
#Bean
public Foobar foobar(#Value("${my.value}") String v) {
return new Foobar(v);
}
}
If my.value is not set, I will get this error message
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myComp' defined in file [/home/stephan/workspaces/workspace_mercateo/demo/target/classes/com/example/MyComp.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [com.example.Foobar] found for dependency [com.example.Foobar]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.Foobar] found for dependency [com.example.Foobar]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
[...]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.Foobar] found for dependency [com.example.Foobar]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
Though spring recognizes that my.value is missing there is nothing about this in the output log.
Is there a way to configure spring so that
1) #Conditional is used
and
2) error message contains "my.value is missing"
?