I have a Component class and a config class,so can we autowire component class which uses #value internally,I tried using it but it throws exception,Can anyone please help me understanding
#Component
public class UserAction {
#Value("${cp.user.name}")
private String userName;
#Value("${cp.user.actiontype}")
private String actionType;
#Value("${cp.user.designation}")
protected Designation designation;
public void show() {
System.out.println(userName);
System.out.println(actionType);
System.out.println(designation);
}
}
#Configuration
#ComponentScan("com.example")
public class AppConfig {
#Autowired
UserAction userAction;
------
}
So My question is : can I autowire my UserAction bean into my AppConfig class?
I tried using it but its throwing exception,so can we autowire a component which internally uses #value :
Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'AppConfig ': Unsatisfied dependency expressed through field 'userAction'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userAction': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'cp.user.actiontype' in value "${cp.user.actiontype}"
Yes you can Autowire beans in Configuration class, but the issue here is that a property in your bean has no value set in properties/yml file
#Value("${cp.user.actiontype}")
set the property cp.user.actiontype in your .properties or .yml file
Related
I'm having a trouble while configuring Spring AOP.
I created an aspect class which is below:
#Slf4j
#Aspect
#RequiredArgsConstructor
#Component
public class LoggingAspect {
private static final Logger logger = CommonLogger.getLogger(LoggingAspect.class);
private final ObjectMapper mapper;
private final JobExecutionService jobExecutionService;
}
Then I added a configuration file:
#Configuration
#EnableAspectJAutoProxy(proxyTargetClass = true)
#RequiredArgsConstructor
public class AspectConfiguration {
private final ObjectMapper objectMapper;
private final JobExecutionService jobExecutionService;
#Bean
public LoggingAspect loggingAspect() {
return new LoggingAspect(objectMapper, jobExecutionService);
}
}
But when I started the application, I am getting below errors:
Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.ClassPathXmlApplicationContext]: Constructor threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'aspectConfiguration' defined in URL: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
I have added aspectjrt and aspectjweaver dependencies to pom.xml.
Spring version is 4.3.6
I couldn't figure out where the problem is. Any help would be appreciated.
Add class:
#Configuration
public class BeanConfig {
#Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
I have a spring boot application where I have enabled mongo auditing. The application starts fine and stores mongo documents with all auditing fields (createdDate, updatedDate, etc.). However, when running unit test I get the following exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoAuditingHandler': Cannot create inner bean '(inner bean)#115c946b' of type [org.springframework.data.mongodb.config.MongoAuditingRegistrar$MongoMappingContextLookup] while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#115c946b': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.convert.MappingMongoConverter' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#115c946b': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.convert.MappingMongoConverter' 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.data.mongodb.core.convert.MappingMongoConverter' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Here is my main class
#SpringBootApplication
#EnableMongoAuditing
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(PatientstoreApplication.class, args);
}
}
And here is my test class:
#WebMvcTest(TestController.class)
public class TestTest {
#Autowired MockMvc mockMvc;
#MockBean TestService testService;
#Test
public void test() {
}
}
A reproducible example can be found here: https://github.com/jota87r/testapp
My question is: is there any configuration missing? should I manually create a bean of type for MappingMongoConverter for my test cases?
You can mock the MappingMongoConverter.class.
So your test class should be as follows:
#WebMvcTest(TestController.class)
public class TestTest {
#Autowired
MockMvc mockMvc;
#MockBean
TestService testService;
//Mock MappingMongoConverter
#MockBean
private MappingMongoConverter mappingMongoConverter;
#Test
public void test() {
}
I encountered the same situation.
In your #WebMvcTest class, try to add a test configuration like:
#TestConfiguration
static class TestConfig {
#Bean
public MappingMongoConverter mongoConverter() {
return new MappingMongoConverter(mock(DbRefResolver.class), mock(MappingContext.class));
}
}
I am trying to run a batch job, where I want to make my SQL query dynamic. But I'm getting an exception while building code as "Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?". Below are the code snippets and exception trace for the same.
BatchConfig
#Configuration
#EnableBatchProcessing
public class StoreSalesBatchConfiguration {
#Autowired
#Qualifier("jobBuilderFactory")
private JobBuilderFactory jobBuilderFactory;
#Autowired
#Qualifier("stepBuilderFactory")
private StepBuilderFactory stepBuilderFactory;
#Autowired
#Qualifier("jobCompletionNotificationListener")
private JobCompletionNotificationListener jobCompletionNotificationListener;
#Autowired
#Qualifier("jobLauncher")
private JobLauncher jobLauncher;
#Autowired
#Qualifier("storeSalesJob")
private Job storeSalesJob;
#Autowired
private GameStoreSalesRepository storeSalesRepository;
#Bean
#StepScope
ItemReader<GameStoreSales> gameStoreSalesReader(#Qualifier("gdwMpsBatch") final DataSource dataSource,
#Value("#{jobParameters[maxDate]}") String maxDate) {
JdbcCursorItemReader<GameStoreSales> databaseReader = new JdbcCursorItemReader<>();
databaseReader.setDataSource(dataSource);
databaseReader.setSql(CommonConstants.STORE_SALES_QUERY);
databaseReader.setPreparedStatementSetter(new PreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, maxDate);
}
});
databaseReader.setRowMapper(new BeanPropertyRowMapper<>(GameStoreSales.class));
return databaseReader;
}
#Bean
public GameStoreSalesProcessor gameStoreSalesProcessor() {
return new GameStoreSalesProcessor();
}
#Bean
public ItemWriter<GameStoreSales> gameStoreSalesWriter() throws Exception {
return new GameStoreSalesWriter();
}
#Bean
public Step gameStoreSalesStep(#Qualifier("gdwMpsBatch") final DataSource dataSource,
#Value("#{jobParameters[maxDate]}") String maxDate) throws Exception {
return stepBuilderFactory.get("gameStoreSalesStep").<GameStoreSales, GameStoreSales>chunk(1000)
.reader(gameStoreSalesReader(dataSource,maxDate)).processor(gameStoreSalesProcessor()).writer(gameStoreSalesWriter()).build();
}
#Bean(name = "storeSalesJob")
public Job storeSalesJob(Step gameStoreSalesStep) {
return jobBuilderFactory.get("storeSalesJob").incrementer(new RunIdIncrementer())
.listener(jobCompletionNotificationListener).flow(gameStoreSalesStep).end().build();
}
#Scheduled(cron = "*/30 * * * * *")
public void runStoreSalesJob() throws JobExecutionAlreadyRunningException, JobRestartException,
JobInstanceAlreadyCompleteException, JobParametersInvalidException {
String dateParam = new Date().toString();
String maxDate = storeSalesRepository.getMaxCalDate();
JobParameters param = new JobParametersBuilder().addString("date", dateParam)
.addString("maxDate", weekEnd)
.toJobParameters();
try{
jobLauncher.run(storeSalesJob, param);
} catch(Exception e){
e.printStackTrace();
}
}
}
Exception Trace:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'storeSalesBatchConfiguration': Unsatisfied dependency expressed through field 'storeSalesJob'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'storeSalesJob' defined in class path resource [com/staples/mpsbatch/config/StoreSalesBatchConfiguration.class]: Unsatisfied dependency expressed through method 'storeSalesJob' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gameStoreSalesStep' defined in class path resource [com/staples/mpsbatch/config/StoreSalesBatchConfiguration.class]: Unsatisfied dependency expressed through method 'gameStoreSalesStep' parameter 1; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'storeSalesJob' defined in class path resource [com/staples/mpsbatch/config/StoreSalesBatchConfiguration.class]: Unsatisfied dependency expressed through method 'storeSalesJob' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gameStoreSalesStep' defined in class path resource [com/staples/mpsbatch/config/StoreSalesBatchConfiguration.class]: Unsatisfied dependency expressed through method 'gameStoreSalesStep' parameter 1; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'gameStoreSalesStep' defined in class path resource [com/staples/mpsbatch/config/StoreSalesBatchConfiguration.class]: Unsatisfied dependency expressed through method 'gameStoreSalesStep' parameter 1; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?
Caused by: org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?
Please suggest why jobParameters are not being recognised and where the configuration is going wrong.
A spring batch StepScope object is one which is unique to a specific step and not a singleton. As you probably know, the default bean scope in Spring is a singleton. But by specifying a spring batch component being StepScope means that Spring Batch will use the spring container to instantiate a new instance of that component for each step execution.
This is often useful for doing parameter late binding where a parameter may be specified either at the StepContext or the JobExecutionContext level and needs to be substituted for a placeholder, much like your example with the filename requirement.
Another useful reason to use StepScope is when you decide to reuse the same component in parallel steps. If the component manages any internal state, its important that it be StepScope based so that one thread does not impair the state managed by another thread (e.g, each thread of a given step has its own instance of the StepScope component).
Try annotating with StepScope:
#Bean
#StepScope
public Step gameStoreSalesStep(#Qualifier("gdwMpsBatch") final DataSource dataSource,
#Value("#{jobParameters[maxDate]}") String maxDate) throws Exception {
return stepBuilderFactory.get("gameStoreSalesStep").<GameStoreSales, GameStoreSales>chunk(1000)
.reader(gameStoreSalesReader(dataSource,maxDate)).processor(gameStoreSalesProcessor()).writer(gameStoreSalesWriter()).build();
}
I'm getting this error while trying to start my app. I've looked at many similar problems and topics but none seems to help me.
Error creating bean with name 'databaseManager': Unsatisfied dependency
expressed through field 'articleRepo'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'pl.dzejkobdevelopment.database.repositories.ArticleRepo' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
#Repository
public interface ArticleRepo extends CrudRepository<Article, Long> {
}
and...
#Service
public class DatabaseManager {
#Autowired
private ArticleRepo articleRepo;
#Autowired
private CommentRepo commentRepo;
#Autowired
private TagRepo tagRepo;
#Autowired
private UserRepo userRepo;
public void addArticle(Article article){
article.getTags().forEach(tag ->addTag(tag));
articleRepo.save(article);
}
public List<Comment> findComments(User user){
return commentRepo.findByCommentAuthor(user);
}
private void addTag(Tag tag){
tagRepo.save(tag);
}
}
and...
#Configuration
//#ComponentScan(basePackages="pl.dzejkobdevelopment.database.repositories")
public class AppConfig {
#Bean
public WebsiteProporties websiteProporties(){
return new WebsiteProporties();
}
#Bean
public StorageProperties storageProporties(){ return new StorageProperties();}
#Bean
public DatabaseManager databaseManager(){ return new DatabaseManager();}
}
}
Uncommenting ComponentScan doesn't help.
EDIT
Changeing ComponentScan for EnableJpaRepositories gives this error:
Error creating bean with name 'databaseManager': Unsatisfied dependency expressed through field 'articleRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'articleRepo': Cannot create inner bean '(inner bean)#14a1d6d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#14a1d6d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
Try to use
#EnableJpaRepositories("pl.dzejkobdevelopment.database.repositories")
instead of ComponentScan.
Im using:
- elasticsearch 5.4.
- Spring boot 1.4.7.RELEASE
- spring-data-elasticsearch 3.0.1.RELEASE.
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.landfiles.farms.repository")
public class ESConfig {
#Value("${elasticsearch.host}")
private String EsHost;
#Value("${elasticsearch.port}")
private Integer EsPort;
#Bean
public Client client() throws Exception {
return new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(
InetAddress.getByName(EsHost), EsPort));
}
#Bean
public ElasticsearchOperations elasticsearchTemplate() throws Exception {
return new ElasticsearchTemplate(client());
}
}
I have a fail on the application run:
java.lang.NoClassDefFoundError: org/springframework/data/mapping/model/Property
Full stackstrace:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Unsatisfied dependency expressed through method 'elasticsearchTemplate' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchConverter' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Unsatisfied dependency expressed through method 'elasticsearchConverter' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingContext' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/mapping/model/Property
Jira's issue linked (not answered) : https://jira.spring.io/browse/DATAES-364
Anybody have a working hello world example ?
Thanks!