org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type - spring

2020-09-23T15:28:00.3483912Z java.lang.IllegalStateException: Failed to load ApplicationContext
2020-09-23T15:28:00.3489821Z Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'salecChannelEventProcessor' defined in file [/home/runner/work/calculation-service/calculation-service/target/classes/com/demo/calculation/saleschannel/SalecChannelEventProcessor.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'de.demo.json.schema.JsonValidator' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
import de.demo.json.schema.JsonValidator;
#Configuration
#ComponentScan( basePackages = {
"com.demo",
"de.demo" },
excludeFilters = {
#ComponentScan.Filter( Configuration.class )
} )
#ImportResource("classpath:/spring-context.xml")
#Import({SwaggerConfig.class, SalesChannelSqsConfig.class})
public class SpringMvcConfig extends WebMvcConfigurationSupport {
#Autowired private ApplicationContext applicationContext;
#Bean( name = "objectMapper" )
public ObjectMapper getObjectMapper( JacksonService jacksonService ) {
return jacksonService.getObjectMapper();
}
#Bean(name = "jsonValidator")
public JsonValidator jsonValidator() {
return new JsonValidator();
}
}
#Component
#Slf4j
#RequiredArgsConstructor
public class SalesChannelUpdateListerner {
#NonNull
private final SalesChannelService salesChannelService;
#NonNull
private final SalecChannelEventProcessor salecChannelEventProcessor;
#SqsListener(value = "${sales.channel.update.queue.name}", deletionPolicy = ON_SUCCESS)
#SneakyThrows
public void receiveSalesChannelUpdateEvent(
#NotificationMessage EnvelopedMessage envelopedMessage) {
log.debug("Received message from sales channel update event queue : {}"
}
#Component
#Slf4j
#RequiredArgsConstructor
public class SalecChannelEventProcessor {
private static final String MESSAGE_TYPE = "sales_channel_update";
#NonNull
private final ObjectMapper objectMapper;
#NonNull
private final JsonValidator jsonValidator;
#SneakyThrows(JsonProcessingException.class)
public boolean isValid(EnvelopedMessage envelopedMessage) {
if (!MESSAGE_TYPE.equals(envelopedMessage.getType())) {
return false;
}
return jsonValidator.validate(envelopedMessage);
}

You need to create the JsonValidator bean. You need to change yor SalecChannelEventProcessor to be:
#Component
#Slf4j
#RequiredArgsConstructor
public class SalecChannelEventProcessor {
private static final String MESSAGE_TYPE = "sales_channel_update";
#NonNull
private final ObjectMapper objectMapper;
#Bean
public JsonValidator jsonValidator(){
return new JsonValidator();
}
#SneakyThrows(JsonProcessingException.class)
public boolean isValid(EnvelopedMessage envelopedMessage) {
if (!MESSAGE_TYPE.equals(envelopedMessage.getType())) {
return false;
}
return jsonValidator().validate(envelopedMessage);
}
}

Related

use spring-data-r2dbc, Unable to inject DAO interface,Field myDao in ServiceImpl required a bean of type 'UmsAddressDao' that could not be found

1.illustrate
springboot 2.3.7
springboot-data-r2dbc 1.1.6
2.I used Spring-Data-R2DBC to operate mysql, but I have been reporting an errororg.springframework.beans.factory.UnsatisfiedDependencyException
3.Complete error description
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webFluxController': Unsatisfied dependency expressed through field 'umsAddressService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'umsAddressServiceImpl': Unsatisfied dependency expressed through field 'umsAddressDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxx.inner.UmsAddressDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Field umsAddressDao in com.xxx.impl.UmsAddressServiceImpl required a bean of type 'com.xxx.inner.UmsAddressDao' that could not be found.
3.My code snippet
my controller
#RestController
public class WebFluxController {
private Logger log = LoggerFactory.getLogger(WebFluxController.class);
#Autowired
private UmsAddressService umsAddressService;
#Autowired
private StringRedisTemplate stringRedisTemplate;
#Autowired
private QuestionService questionService;
// do something
}
my service
public interface UmsAddressService {
Mono<UmsAddress> findById(Long id);
}
my service impl
#Service
public class UmsAddressServiceImpl implements UmsAddressService {
#Autowired
private UmsAddressDao umsAddressDao;
#Override
public Mono<UmsAddress> findById(Long id) {
return umsAddressDao.findById(id);
}
}
my dao
#Component
public interface UmsAddressDao extends ReactiveCrudRepository<UmsAddress,Long> {
}
my model
#Data
#Accessors(chain = true)
#ToString
#Table("ums_address")
public class UmsAddress {
#Id
#Column("id")
private Long id;
#Column("member_id")
private Long memberId;
// other field
}
springbootApplication
#EnableWebFlux
#SpringBootApplication( exclude = { RedisRepositoriesAutoConfiguration.class })
#OpenAPIDefinition(info = #Info(title = "APIs", version = "1.0", description = "Documentation APIs v1.0"))
public class MyWebApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(RollkingWebApplication.class).web(WebApplicationType.REACTIVE).run(args);
}
}

Unsatisfied dependency expressed through constructor parameter 1 with userRepository

In a spring boot application who are reactive and use jwt, in my spring-cloud-gateway, I have this code.
#EnableDiscoveryClient
#SpringBootApplication
public class GatewayServiceApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayServiceApplication.class, args);
}
}
#Configuration
#EnableWebFluxSecurity
#EnableReactiveMethodSecurity
public class SpringSecurityWebFluxConfig {
private final UserServiceImpl userService;
private final JwtTokenUtil tokenUtil;
private static final String[] AUTH_WHITELIST = {
"/resources/**",
"/webjars/**",
"/authorize/**",
"/favicon.ico"};
public SpringSecurityWebFluxConfig(JwtTokenUtil tokenUtil, UserServiceImpl userService) {
this.tokenUtil = tokenUtil;
this.userService = userService;
}
..
}
#Service
public class UserServiceImpl implements ReactiveUserDetailsService, UserService {
private final UserRepository userRepository;
public UserServiceImpl(final UserRepository userRepository) {
this.userRepository = userRepository;
}
...
}
#Repository
public interface UserRepository extends ReactiveCrudRepository<User, Integer>{
}
public class JWTHeadersExchangeMatcher implements ServerWebExchangeMatcher {
#Override
public Mono<MatchResult> matches(final ServerWebExchange exchange) {
}
}
public class JWTReactiveAuthenticationManager implements ReactiveAuthenticationManager {
...
public JWTReactiveAuthenticationManager(final PasswordEncoder passwordEncoder, final UserServiceImpl userService) {
this.passwordEncoder = passwordEncoder;
this.userService = userService;
}
}
public class JwtTokenUtil {
...
}
public class TokenAuthenticationConverter implements Function<ServerWebExchange, Mono<Authentication>> {
private final JwtTokenUtil tokenProvider;
public TokenAuthenticationConverter(JwtTokenUtil tokenProvider) {
this.tokenProvider = tokenProvider;
}
}
public class TokenAuthenticationConverter implements Function<ServerWebExchange, Mono<Authentication>> {
private final JwtTokenUtil tokenProvider;
public TokenAuthenticationConverter(JwtTokenUtil tokenProvider) {
this.tokenProvider = tokenProvider;
}
}
[ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'springSecurityWebFluxConfig' defined in
file
[/home/mac/Development/project/reactive-cloud/gateway-service/build/classes/java/main/com/example/gatewayservice/config/SpringSecurityWebFluxConfig.class]:
Unsatisfied dependency expressed through constructor parameter 1;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userServiceImpl' defined in file
[/home/mac/Development/project/reactive-cloud/gateway-service/build/classes/java/main/com/example/gatewayservice/service/UserServiceImpl.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.example.gatewayservice.repository.UserRepository' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {} 2019-06-27 11:47:23.336 INFO 53073 --- [
main] ConditionEvaluationReportLoggingListener :
Tried to put autowired
on UserServiceImpl in SpringSecurityWebFluxConfig class
on UserRepository in UserServiceImpl class
on UserServiceImpl in JWTReactiveAuthenticationManager.class
but get same error
Edit
if i use
#EnableR2dbcRepositories to GatewayServiceApplication, I dont't have this error but it search about DatabaseClient
Please add #Autowired annotation in UserServiceImpl class for UserRepository variable in constitute constructor or variable level.

How to do integration testing for custom mongo repository?

These are the following configuration that I have done in my project.
#Configuration
public class AppMongoConfig {
#Autowired private MongoDbFactory mongoDbFactory;
#Autowired private MongoMappingContext mongoMappingContext;
#Bean
public MappingMongoConverter mappingMongoConverter() {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return converter;
}
}
#Configuration
#RequiredArgsConstructor
#EnableConfigurationProperties(MultipleMongoProperties.class)
public class MultipleMongoConfig {
private final MultipleMongoProperties mongoProperties;
#Primary
#Bean(name = "primaryMongoTemplate")
public MongoTemplate primaryMongoTemplate() throws Exception {
return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
}
#Bean(name = "secondaryMongoTemplate")
public MongoTemplate secondaryMongoTemplate() throws Exception {
return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
}
#Bean
#Primary
public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
}
#Bean
public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
}
}
#Data
#ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {
private MongoProperties primary = new MongoProperties();
private MongoProperties secondary = new MongoProperties();
}
#Configuration
#EnableMongoRepositories(
basePackages = {"com.student.repository.primary"},
mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {}
#Configuration
#EnableMongoRepositories(
basePackages = {"com.student.repository.secondary"},
mongoTemplateRef = "secondaryMongoTemplate")
public class SecondaryMongoConfig {}
Repository code:
public interface StudentDAO {
Student save(StudentInfo studentInfo);
}
#Repository
public class StudentDAOImpl implements StudentDAO {
#Autowired #Qualifier("primaryMongoTemplate")
private MongoTemplate mongoTemplate;
#Override public StudentInfo save(StudentInfo userWatchlist) {
return mongoTemplate.save(userWatchlist);
}
}
Integration Testing code:
#RunWith(SpringRunner.class)
#DataMongoTest(includeFilters = #Filter(Repository.class))
public class WatchListDAOImplIT {
#Autowired private StudentDAO studentDAO;
#Test
public void save() {
StudentInfo studentInfo = getStudentInfo();
StudentInfo dbUserWatchlist = watchListDAO.save(studentInfo);
Assert.assertEquals(studentInfo.getId(), dbUserWatchlist.getId());
}
private StudentInfo getStudentInfo() {
StudentInfo studentInfo = new StudentInfo();
studentInfo.setId(9999999l);
return studentInfo;
}
}
Which is giving me following error:-
java.lang.IllegalStateException: Failed to load ApplicationContext
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at
org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:
: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'appMongoConfig': Unsatisfied dependency
expressed through field 'mongoDbFactory'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'primaryFactory' defined in class path
resource [.../config/mongo/MultipleMongoConfig.class]: Unsatisfied
dependency expressed through method 'primaryFactory' parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.mongo.MongoProperties'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.mongo.MongoProperties'
available: expected at least 1 bean which

Spring: Register a component within a test class

I am registering an ErrorHandler for my Spring Scheduler and would like to test that is is correctly registered in a SpringTest
So far I have tried:
Handler
#Component
public class ScheduledErrorHandler implements ErrorHandler {
#Autowired
private ErrorService errorService;
#Override
public void handleError(final Throwable t) {
errorService.handle(t);
}
}
Registering the Handler
#EnableScheduling
#Configuration
public class SchedulingConfiguration implements SchedulingConfigurer {
#Autowired
private ScheduledErrorHandler handler;
#Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(1);
scheduler.setErrorHandler(handler);
scheduler.initialize();
taskRegistrar.setScheduler(scheduler);
}
//...
}
Testing it's registered
#ContextConfiguration(classes = {
SchedulerConfiguration.class,
SchedulerErrorHandler.class
})
#RunWith(SpringRunner.class)
public class SchedulerErrorHandlerTest {
#MockBean
private ErrorService service;
#Autowired
private ExampleScheduledJob job;
#Test
public void verifyHandlerGetsCalled() {
// Wait until the job runs
if(!job.latch.await(5, SECONDS)) {
fail("Job never ran");
}
verify(service).handle(any(RuntimeException.class));
}
#Component
public static class ExampleScheduledJob {
private final CountDownLatch latch = new CountDownLatch(1);
#Scheduled(fixedRate=1000)
public void run() {
latch.countDown();
throw new RuntimeException("error");
}
}
}
However when I do this I get a DependencyNotFound error saying Spring cannot create my test class as no Bean named ExampleScheduledJob can be found. How can I register it only for the sake of this test?
Error creating bean with name
'com.example.demo.SchedulerErrorHandlerTest': Unsatisfied dependency
expressed through field 'job'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.example.demo.SchedulerErrorHandlerTest$ExampleScheduledJob'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
This should work
#ContextConfiguration(classes = {
SchedulingConfiguration.class,
SchedulerErrorHandlerTest.ExampleScheduledJob.class,
ScheduledErrorHandler.class
})
#RunWith(SpringRunner.class)
You can register your test configuration class (ExampleScheduledJob) as indicated above. Since it is a static inner class, you need to use it like SchedulerErrorHandlerTest.ExampleScheduledJob

Not a managed type during app context initialization

I cannot figure out why entity objects cannot be managed by DAO classes.
I have the following PersistenceConfig file:
#Configuration
#EnableTransactionManagement
#PropertySource({"classpath:persistence"})
#EnableJpaRepositories("com.wx.rm")
public class PersistenceConfig {
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[]{"com.wx.rm"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource restDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
setProperty("hibernate.globally_quoted_identifiers",
env.getProperty("hibernate.globally_quoted_identifiers"));
}
};
}
}
Interface IFooAdvertDao:
#Repository("fooAdvertDao")
public interface IFooAdvertDao extends GenericDao<FooAdvert, String> {
}
Interface IBarAdvertDao:
#Repository("barAdvertDao")
public interface IBarAdvertDao extends GenericDao<BarAdvert, Integer> {
}
Base entity BaseAdvert class:
#MappedSuperclass
public abstract class BaseAdvert implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "link")
private String link;
#Column(name = "rooms")
private BigDecimal rooms;
public BaseAdvert() {
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public BigDecimal getRooms() {
return rooms;
}
public void setRooms(BigDecimal rooms) {
this.rooms = rooms;
}
}
Entity FooAdvert class:
#Entity
#Table(name = "foo_adverts")
#DynamicUpdate
public class FooAdvert extends BaseAdvert implements Serializable {
#Id
private String id;
#Column(name = "type")
private Integer type;
public FooAdvert() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
}
Entity BarAdvert class:
#Entity
#Table(name = "bar_adverts")
#DynamicUpdate
public class BarAdvert extends BaseAdvert implements Serializable {
#Id
private Integer id;
#Column(name = "status")
private Integer status;
public BarAdvert() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
That`s my GenericDao class:
#Repository
public interface GenericDao<T extends Serializable, ID extends Serializable> extends JpaRepository<T, ID> {
}
Generic service class:
public interface GenericService <T extends Serializable, ID extends Serializable> {
T findOne(final ID id);
Page<T> findAll(final Pageable pageable);
long count();
}
Generic service implementation class:
#Service
#Transactional
public class GenericServiceImpl <T extends Serializable, ID extends Serializable> implements GenericService<T, ID> {
#Autowired
private GenericDao<T, ID> genericDao;
public GenericServiceImpl() {
}
public GenericServiceImpl(GenericDao<T, ID> genericDao) {
this.genericDao = genericDao;
}
#Override
#Transactional(readOnly = true)
public T findOne(ID id) {
return genericDao.findOne(id);
}
#Override
#Transactional(readOnly = true)
public Page<T> findAll(Pageable pageable) {
return genericDao.findAll(pageable);
}
#Override
#Transactional(readOnly = true)
public long count() {
return genericDao.count();
}
}
FooAdvertService:
#Service
public class FooAdvertService extends GenericServiceImpl<FooAdvert, String> {
#Autowired
private IFooAdvertDao fooAdvertDao;
}
FooAdvertController class:
#RestController
#RequestMapping("/api")
public class FooAdvertController {
#Autowired
private FooAdvertService fooAdvertService;
#GetMapping("count")
public ResponseEntity getAdvertsCount() {
Long advertsCount = fooAdvertService.count();
return new ResponseEntity(advertsCount, HttpStatus.OK);
}
}
Error message when I try to run my app:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fooAdvertController': Unsatisfied dependency expressed through field 'fooAdvertService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fooAdvertService': Unsatisfied dependency expressed through field 'genericDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fooAdvertDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.wixanz.rm.ads.domain.FooAdvert
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fooAdvertService': Unsatisfied dependency expressed through field 'genericDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fooAdvertDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.wixanz.rm.ads.domain.FooAdvert
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fooAdvertDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.wixanz.rm.ads.domain.FooAdvert
Caused by: java.lang.IllegalArgumentException: Not a managed type: class org.wixanz.rm.ads.domain.FooAdvert
at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
try to autowire the IFooAdvertDao by name
#Service
public class FooAdvertService extends GenericServiceImpl<FooAdvert, String>
{
#Autowired
#Qualifier("fooAdvertDao")
private IFooAdvertDao fooAdvertDao;
}

Resources