I want to test my controller by using #WebMvcTest. I #MockBean the dependencies of the controller but when running the test, it fails to start. The application starts correctly when running the main class.
The Test:
#RunWith(SpringRunner.class)
#WebMvcTest(MetricResource.class)
public class MetricResourceTest {
#Autowired
private MockMvc mvc;
#MockBean
private MetricService metricService;
#MockBean
private MetricMapper metricMapper;
#Test
public void test() {
}
}
The Controller:
#RestController
#RequestMapping("/api/v1/metrics")
public class MetricResource {
private final MetricService metricService;
private final MetricMapper metricMapper;
public MetricResource(MetricService metricService, MetricMapper metricMapper) {
this.metricService = metricService;
this.metricMapper = metricMapper;
}
#GetMapping
public ResponseEntity<List<MetricDto>> getMetrics(#RequestParam(required = false) List<String> fields) {
if (fields == null) {
fields = new ArrayList<>();
}
List<Metric> metrics = metricService.getMetric(fields);
List<MetricDto> dto = metricMapper.fromMetric(metrics);
return ResponseEntity.ok(dto);
}
}
The error:
Description:
Parameter 2 of constructor in com.sps.soccer.service.SoccerService required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'soccerService' defined in file [K:\home\projects\stable\sps-backend\sps-soccer\target\classes\com\sps\soccer\service\SoccerService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'soccerAnalysisRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'soccerAnalysisRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
The SoccerService has a dependency on SoccerAnalysisRepository which is a MongoRepository. I don't understand why the SoccerService is created by the test since #Service are not scanned by #WebMvcTest.
The application is a Maven multi modules, so I has to explicitly configure the component scanning and repository.
#SpringBootApplication
#ComponentScan(basePackages = {"com.sps.soccer", "com.sps.sdql", "com.sps.core", "com.sps.web"},
excludeFilters = {
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.sdql.configuration.ClockConfiguration.class),
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.soccer.configuration.ClockConfiguration.class),
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.sdql.configuration.RestConfiguration.class),
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.soccer.configuration.RestConfiguration.class)
})
#EnableMongoRepositories(basePackages = {"com.sps.soccer", "com.sps.sdql", "com.sps.core"})
public class SpsWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpsWebApplication.class, args);
}
}
You must move all area-specific configuration, like #ComponentScan and #EnableMongoRepositories, to a separate #Configuration file. It's important not to litter the application’s main class with configuration settings that are specific to a particular area of its functionality.
More information: https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-user-configuration
Related
#DataJpaTest
class DataJpaVerificationTest {
#Autowired
private JdbcTemplate template;
#Test
public void testTemplate() {
assertThat(template).isNotNull();
}
}
When I run this test I get the following error:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'kafkaConfig' defined in file
[***\config\KafkaConfig.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.kafka.KafkaProperties'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}
where KafkaConfig class is a part of my application (app read data from Kafka and saves data to DB) and looks like:
#Configuration
#RequiredArgsConstructor
public class KafkaConfig {
private final KafkaProperties kafkaProperties;
#Bean
public Properties consumerProperties() {
Properties props = new Properties();
props.putAll(this.kafkaProperties.buildConsumerProperties());
return props;
}
}
Based on information that I googled about DataJpaTest annotation:
created application context will not contain the whole context needed
for our Spring Boot application, but instead only a “slice” of it
containing the components needed to initialize any JPA-related
components like our Spring Data repository.
So the question is: why Spring tries to load to the context Kafka specific bean for DataJpaTest?
Error: Parameter 0 of constructor in com.tw.api.service.impl.BookServiceImpl required a bean of type 'com.tw.api.repository.BookRepository' that could not be found.
Exception: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookController' defined in file [/Users/rashdul.ehasan/Projects/boot-camp/api/target/classes/com/tw/api/controller/BookController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImpl' defined in file [/Users/rashdul.ehasan/Projects/boot-camp/api/target/classes/com/tw/api/service/impl/BookServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tw.api.repository.BookRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations
Any idea on how to fix this?
I have excluded the default auto configuration...
#SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class})
public class ApiApplication {
I have written a factory bean class for mongo but it does not seem to reach there.
#Configuration
#ConditionalOnProperty(prefix = "spring", name = "db.dialect", havingValue = "mongo", matchIfMissing = true)
#EnableMongoRepositories(
repositoryFactoryBeanClass = ApiMongoRepositoryFactoryBean.class,
basePackages = "com.tw.api.repository")
public class ApiMongoRepositoryConfig {
#Value("${spring.data.mongodb.uri}")
private String uri;
private static final Logger LOGGER = LoggerFactory.getLogger(ApiMongoRepositoryConfig.class);
public ApiMongoRepositoryConfig() {
LOGGER.info("Repository Configuration: " + ApiMongoRepositoryConfig.class);
}
#Bean
public MongoClient mongoClient() {
return new MongoClient(new MongoClientURI(uri));
}
}
Packages:
BookController: package com.tw.api.controller;
BookService: package com.tw.api.service;
BookServiceImpl: package com.tw.api.service.impl;
BookRepository: package com.tw.api.repository;
ApiMongoRepository: package com.tw.api.repository.base;
ApiMongoRepositoryConfig: package com.tw.api.config;
ApiMongoRepositoryFactoryBean: package com.tw.api.helper;
ApiApplication: package com.tw.api;
Here is the link to the code base, https://github.com/er310/boot-camp/tree/master/api
You have your Book class marked as a JPA entity:
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "book")
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Book extends AbstractEntity {
But you are only creating Mong repositories with #EnableMongoRepositories.
You need to make up your mind if you want to use MongoDb with Spring Data Mongo or a relational database with JPA + Spring Data JPA.
I get an error when I try to execute SpringBoot. because I need a " bean ", I don't understand why I get this, I have all annotations
17-09-2018 12:24:53.905 [restartedMain] WARN o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext.refresh - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterController': Unsatisfied dependency expressed through field 'pgService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterServiceImp': Unsatisfied dependency expressed through field 'pgRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'es.my.repository.ParameterRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
With more error :
APPLICATION FAILED TO START
Description:
Field pgRepository in es.service.ParameterServiceImp required a bean of type 'es.repository.ParameterRepository' that could not be found.
Action:
Consider defining a bean of type 'es.repository.ParameterRepository' in your configuration.
I have in my controller -> with #Autowired
#RestController
#RequestMapping(value = { "/param" })
#CrossOrigin
public class ParameterController {
#Autowired
ParameterService pgService;
#RequestMapping(method = RequestMethod.GET, value = "/get", produces =
MediaType.APPLICATION_JSON_VALUE)
public List<Parameter> getAllParameters() {
List<Parameter> list = pgService.selectAll();
return list;
}
In my service -> I don't use annotations
public interface ParameterService {
public List<Parameter> selectAll();
}
Imple-> I use Service and Autowired
#Service
public class ParameterServiceImp implements ParameterService {
#Autowired
ParameterRepository pgRepository;
public List<Parameter> selectAll() {
return pgRepository.findAll());
}
}
Repository -> Here , I have querys.
public interface ParameterRepository extends CrudRepository<Parameter, String> {
}
Model ->
My POJO
#Entity
#Table(name = "Parameter")
public class Parameter {
#Id
#NotNull
#Column(name = "ID")
private String id;
#NotNull
#Column(name = "name")
private String name;
// getters setters and construct
}
I have #Entity , #Service , #Autowired but I get an error
If you use #SpringBootApplication with no basePackage specified, it will default to the current package. Just like you add #ComponentScan and #EnableJpaRepositories with no base package.
If you have set a different package to #SpringBootApplication make sure you also add #EnableJpaRepositories with proper basePackage. Repositories won't be recognized only by #ComponentScan(or declaring them as beans by any other ways explicitly or implicitly).
Try adding the next annotation.
#EnableJpaRepositories(basePackages = {"<repository-package-here>"})
is a.some.package package for your #SpingbootApplication?
other wise you need to add component scan annotation for your base package that is a.some.package
I have two config here:
#Configuration
public class DataConfig {
#Value("${datasource.jdbcUrl}")
private String jdbcUrl;
#Value("${datasource.username}")
private String username;
#Value("${datasource.password}")
private String password;
#Value("${datasource.driverClassName:com.mysql.jdbc.Driver}")
private String driverClassName;
#Value("${datasource.initialSize:20}")
private int initialSize;
#Value("${datasource.maxActive:30}")
private int maxActive;
#Value("${datasource.minIdle:20}")
private int minIdle;
#Value("${datasource.transactionTimeoutS:30}")
private int transactionTimeoutS;
#Value("${datasource.basePackage:com.tg.ms.mapper}")
private String basePackage;
#Value("${datasource.mapperLocations}")
private String mapperLocations;
#Bean
public DataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setMaxWait(maxWait);
ds.setValidationQuery(validationQuery);
ds.setRemoveAbandoned(removeAbandoned);
ds.setRemoveAbandonedTimeout(removeAbandonedTimeout);
ds.setTestWhileIdle(testWhileIdle);
ds.setTestOnReturn(testOnReturn);
ds.setTestOnBorrow(testOnBorrow);
ds.setMinIdle(minIdle);
return ds;
}
#Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
---------- Another Config -------------
#Configuration
#AutoConfigureAfter(DataBaseConfig.class)
public class MapperScannerConfig {
#Value("${datasource.basePackage:com.tg.ms.mapper}")
private String basePackage;
#Bean
public MapperScannerConfigurer BPMapperScannerConfigurer() {
System.out.println("mapper--1.----******----"+basePackage+"----*******");
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.tg.mapper");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
return mapperScannerConfigurer;
}
}
Can I put#Bean public MapperScannerConfigurer BPMapperScannerConfigurer() into DataConfig? I try but print:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'testMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testMapper' defined in file [/Users/twogoods/codesource/mainetset/target/classes/com/tg/mapper/TestMapper.class]: Cannot resolve reference to bean 'sqlSessionFactoryBean' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactoryBean' defined in class path resource [com/tg/config/DataConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactoryBean' threw exception; nested exception is java.lang.NullPointerException
MapperScannerConfig init earlier than DataConfig, I get it from print log,#Value("${datasource.basePackage:com.tg.ms.mapper}") private String basePackage;can not get value(in DataConfig can get),I use #AutoConfigureAfter is useless,MapperScannerConfig is also eariler, I can not config mapper basePackage
log:Cannot enhance #Configuration bean definition 'BPMapperScannerConfigurer' since its singleton instance has been created too early. The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
I got the same problem. MapperScannerConfigurer is initialized too early in spring framework and ,i think it causes the annotation #AutoConfigureAfter become useless.
So i solve it like : avoid the use of MapperScannerConfigurer:
two ways:
just use #MapperScan("com.a.b.package")
use annotation #org.apache.ibatis.annotations.Mapper in your mybatis mapper interface.
I'd like to create an autowired bean in a Dao class in order to do logging opperations. My way was hitherto static final statement like this:
private static final Log log = LogFactory.getLog(LoggedClass.class);
But now I'm trying to use IoC to turn classes decoupled.
If just add configuration in pom.xml and try to do sth like
#Autowired
Log log;
I receive an error message:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'funciDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.apache.commons.logging.Log br.com.bb.dirco.dao.impl.FunciDaoImpl.log; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'log' defined in class path resource [com/company/project/util/PersistenceConfig.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.Class]: : No qualifying bean of type [java.lang.Class] found for dependency: 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 [java.lang.Class] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
In order to get a logger, I had to provide a class to getLog method on LogFactory class and attribute it to Log instance. There's a way to do it using #Autowired Spring IoC? Thanks!
You can inject only those objects which are managed/created by Spring container. You have to register your bean (or factory method creating the bean) with container (with annotations like #Component/#Singleton/... or directly in xml)
In your case it's not very applicable since you have to have many different types (for every class) of logger objects provided by Spring and then when you inject they would have to be identified by different name/type for every class.
P.S. I don't see any problem using it the way you use it now
Where I work we have implemented support for #Autowired SLF4J Loggers using Springs BeanPostProcessor.
First you need to define an Logger placeholder bean in your application context. This bean is going to be injected by Spring into all bean with a #Autowired Logger field.
#Configuration
public class LoggerConfig {
#Bean
public Logger placeHolderLogger() {
return PlaceHolder.LOGGER;
}
#Bean
public AutowiredLoggerBeanPostProcessor loggerPostProcessor() {
return new AutowiredLoggerBeanPostProcessor();
}
}
Then you an AutowiredLoggerBeanPostProcessor which inspects all beans, indetify bean that contain Logger fields annotated with #Autowired (at this point should contain a reference to the Logger placeholder bean), create a new Logger for the partilcar bean an assigned it to the fields.
#Component
public class AutowiredLoggerBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
#Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
attachLogger(bean);
return bean;
}
#Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
attachLogger(bean);
return bean;
}
private void attachLogger(final Object bean) {
ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
if (Logger.class.isAssignableFrom(field.getType()) &&
(field.isAnnotationPresent(Autowired.class) ||
field.isAnnotationPresent(Inject.class))) {
ReflectionUtils.makeAccessible(field);
if (field.get(bean) == PlaceHolder.LOGGER) {
field.set(bean, LoggerFactory.getLogger(bean.getClass()));
}
}
}
});
}
#Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}