Spring #Conditional: Error Message - java

#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"
?

Related

How do you test a reactive mongo repository?

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

UnsatisfiedDependencyException: Error creating bean with name in 2.4.1 Spring Boot

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

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
}

Unsatisfied Dependency Error through field in Spring

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

Spring: No matching bean found which qualifies as autowire

Application-Context is correctly setup!
Heres my class scenario
public interface IManager
{
public void doStuff();
}
#Component
public abstract class ManagerAction implements IManager
{
#Async
#Override
public void doStuff()
{
//doing stuff
}
public abstract manageWorker();
}
#Component
public class Working extends ManagerAction
{
#Override
public manageWorker()
{
//some busy code
}
}
#Component
public class NotWorking extends ManagerAction
{
#Override
public manageWorker()
{
//some busy code
}
}
#Service
public class BusinessWorker
{
#Autowire
private IManager manager_;
public void preformTasks()
{
manager_.doStuff();
}
}
Heres my error
ERROR [main] (ContextLoader.java:307) - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BusinessWorker': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.B
eanCreationException: Could not autowire field: private com.background.IManager com.background.BusinessWorker.manager_; nested exception is org.springframework.beans.
factory.NoSuchBeanDefinitionException: No matching bean of type [com.background.IManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for
this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.background.IManager com.background.BusinessWorker.manager_;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.background.IManager] found for dependency: expected at least 1
bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 28 more
Application-Context
<mvc:annotation-driven />
<task:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.background" />
The error message says it all: you try to autowire an instance of IManager, but two different Spring components implement this interface, so Spring doesn't know which one to autowire. You need to use the #Qualifier annotation to specify which one you want Spring to autowire.

Categories

Resources