I have an entity class called Screenshot and and a repository declared as this:
public interface ScreenshotRepository extends JpaRepository<Screenshot, UUID>, ScreenshotRepositoryCustom
The custom repository is defined like this:
interface ScreenshotRepositoryCustom
and
class ScreenshotRepositoryImpl implements ScreenshotRepositoryCustom {
private final ScreenshotRepository screenshotRepo;
#Autowired
public ScreenshotRepositoryImpl(ScreenshotRepository screenshotRepo) {
this.screenshotRepo = screenshotRepo;
}
This is following what's described in this other Stack Overflow question: How to add custom method to Spring Data JPA
Now, IntelliJ is giving me a warning:
Autowired members must be defined in a valid Spring bean
I tried adding these annotations to ScreenshotRepositoryImpl but none of the worked:
#Repository
#Component
#Service
but none work. Obviously some are wrong but I was experimenting. What's the correct annotation.
With #Repository, I get this error:
2017-11-23 12:30:04.064 WARN 20576 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'screenshotsController' defined in file [C:\Users\pupeno\Documents\Dashman\java\dashmanserver\out\production\classes\tech\dashman\server\controllers\ScreenshotsController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'screenshotRepositoryImpl' defined in file [C:\Users\pupeno\Documents\Dashman\java\dashmanserver\out\production\classes\tech\dashman\server\models\ScreenshotRepositoryImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'screenshotRepositoryImpl': Requested bean is currently in creation: Is there an unresolvable circular reference?
2017-11-23 12:30:04.064 INFO 20576 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-11-23 12:30:04.064 INFO 20576 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2017-11-23 12:30:04.080 INFO 20576 --- [ restartedMain] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-23 12:30:04.080 ERROR 20576 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
screenshotsController defined in file [C:\Users\pupeno\Documents\Dashman\java\dashmanserver\out\production\classes\tech\dashman\server\controllers\ScreenshotsController.class]
┌─────┐
| screenshotRepositoryImpl defined in file [C:\Users\pupeno\Documents\Dashman\java\dashmanserver\out\production\classes\tech\dashman\server\models\ScreenshotRepositoryImpl.class]
└─────┘
What is happening?
Your dependencies form a cycle: ScreenshotRepository extends ScreenshotRepositoryCustom, but the ScreenshotRepositoryCustom implementation depends on ScreenshotRepository. Because of this cycle, none of the beans can complete their instantiation.
Proposed solution
Spring Data does not support injection via constructor in these scenarios. Attempting to do so will result in a dependency cycle error. To be able to inject ScreenshotRepository into ScreenShotRepositoryImpl, you'd need to do injection via field:
#Repository
public class ScreenshotRepositoryImpl implements ScreenshotRepositoryCustom {
#Autowired
ScreenshotRepository screenshotRepository ;
...
}
Related
I was trying to create my basic spring application and try to connect to my MongoDB database.
so a create my entity
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
#Data #AllArgsConstructor #NoArgsConstructor #ToString
public class MyProduct {
#Id
private String id;
private String name;
private int price;
}
my repository
import com.nizar.back.demo.entities.MyProduct;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource
public interface MyProductRepository extends MongoRepository<MyProduct,String> {
}
my application.properties
server.port=8093
spring.data.mongodb.uri=mongodb://<my username>:<my password>#cluster0.zgrrb.mongodb.net/appDatabase?retryWrites=true&w=majority
and this is my application class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
#SpringBootApplication
#EnableAutoConfiguration(exclude={ DataSourceAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
what i notice that i have this error when i try to run my application, and i didn't understant why ?
2021-07-21 18:04:49.921 INFO 7524 --- [ main] com.nizar.back.demo.DemoApplication : Starting DemoApplication using Java 1.8.0_291 on DESKTOP-6PB4U74 with PID 7524 (C:\dev projects\spring project\demo\target\classes started by abdel in C:\dev projects\spring project\demo)
2021-07-21 18:04:49.924 INFO 7524 --- [ main] com.nizar.back.demo.DemoApplication : No active profile set, falling back to default profiles: default
2021-07-21 18:04:50.411 INFO 7524 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-07-21 18:04:50.459 INFO 7524 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 43 ms. Found 1 MongoDB repository interfaces.
2021-07-21 18:04:50.724 WARN 7524 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myProductRepository' defined in com.nizar.back.demo.dao.MyProductRepository defined in #EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
2021-07-21 18:04:50.732 INFO 7524 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-07-21 18:04:50.749 ERROR 7524 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'mongoTemplate' that could not be found.
I just did this project to learn about spring boot. and i just need to find why i have this error and how i can solve it
it didn't choose the right version of the driver.
so I change the drive version on https://cloud.mongodb.com/ to 3.4 or later and it give me an other url to connect and it work
mongodb://<MyUsername>:<Mypassword>#cluster0-shard-00-00.zgrrb.mongodb.net:27017,cluster0-shard-00-01.zgrrb.mongodb.net:27017,cluster0-shard-00-02.zgrrb.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-sr24zl-shard-0&authSource=admin&retryWrites=true&w=majority
I just started to work with Spring. I followd some tutorials to create a Spring Web MVC project which works. It is a simple project which displays some information as website using thymeleaf.
Now I wanted to add a couchbase database for storing data, I already worked with couchbase for simple .Net Apps. So I followed the tutorial on the official couchbase blog to create a service for the connection to couchbase. Couchbase with Spring-Boot and Spring Data
But when I try to autowire the service I get the following error message:
[main] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcher'
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Multiple Spring Data modules found, entering strict repository configuration mode!
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Bootstrapping Spring Data repositories in DEFAULT mode.
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 70ms. Found 1 repository interfaces.
[main] WARN org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'indexController': Unsatisfied dependency expressed through field 'buildingService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xplorg.model.BuildingService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
[main] ERROR org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'indexController': Unsatisfied dependency expressed through field 'buildingService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xplorg.model.BuildingService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
As far as I understand the message, found Spring the repository but it does not qualify as autowire candidate.
My WebConfig:
#Configuration
#EnableWebMvc
#ComponentScan("com.project.controller")
#ComponentScan("com.xplorg.model")
#EnableCouchbaseRepositories(basePackages = {"com.project.model"})
public class MvcWebConfig implements WebMvcConfigurer {
// Code for generating templateEngine/Resolver ...
}
My controller (here I try to autowire the service, not sure if it is the correct place, causes the exception):
#Controller
public class IndexController {
private int count = 0;
#Autowired
private BuildingService buildingService;
// This line causes the exception
#GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Welcome to Hello World");
return "index";
}
// Some more mapping no use of service
}
My BuildingService:
public interface BuildingService {
Building save(Building building);
Building findById(String buildingId);
List<Building> findByCompanyId(String companyId);
Building findByCompanyAndAreaId(String companyId, String areaId);
List<Building> findByCompanyIdAndNameLike(String companyId, String name, int page);
List<Building> findByPhoneNumber(String telephoneNumber);
Long countBuildings(String companyId);
}
My BuildingServiceImpl:
#Service("BuildingService")
public class BuildingServiceImpl implements BuildingService {
#Autowired
private BuildingRepository buildingRepository;
#Override
public List<Building> findByCompanyId(String companyId) {
return buildingRepository.findByCompanyId(companyId);
}
public List<Building> findByCompanyIdAndNameLike(String companyId, String name, int page) {
return buildingRepository.findByCompanyIdAndNameLikeOrderByName(companyId, name, new PageRequest(page, 20))
.getContent();
}
#Override
public Building findByCompanyAndAreaId(String companyId, String areaId) {
return buildingRepository.findByCompanyAndAreaId(companyId, areaId);
}
#Override
public List<Building> findByPhoneNumber(String telephoneNumber) {
return buildingRepository.findByPhoneNumber(telephoneNumber);
}
#Override
public Building findById(String buildingId) {
return buildingRepository.findById(buildingId).get();
}
#Override
public Building save(Building building) {
return buildingRepository.save(building);
}
#Override
public Long countBuildings(String companyId) {
return buildingRepository.countBuildings(companyId);
}
}
The order classes are simple copied from the tutorial.
Project sturcture:
src/main/java
com.project
config
MvcWebApplicationInitializer
MvcWebConfig
controller
IndexController
model
Area
Building
BuildingRepository
BuildingService
BuildingServiceImpl
EDIT
At the end of the error message the following line stands, could that mean I am missing a dependency?
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'couchbaseRepositoryOperationsMapping' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:769)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
EDIT 2
After trying different approaches and reading more about Spring/Couchbase and Autowired, I now get the exception that No bean named 'couchbaseRepositoryOperationsMapping' available. The whole exception looks like this:
[main] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcher'
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Bootstrapping Spring Data repositories in DEFAULT mode.
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 63ms. Found 1 repository interfaces.
[main] WARN org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'buildingServiceImpl': Unsatisfied dependency expressed through field 'buildingRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingRepository': 'buildingRepository' depends on missing bean 'couchbaseRepositoryOperationsMapping'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'couchbaseRepositoryOperationsMapping' available
[main] ERROR org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'buildingServiceImpl': Unsatisfied dependency expressed through field 'buildingRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingRepository': 'buildingRepository' depends on missing bean 'couchbaseRepositoryOperationsMapping'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'couchbaseRepositoryOperationsMapping' available
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
I'm trying to create unit/integration test using Junit5 for specific service classes to avoid overload the whole project.
So here I try to run the EmailService with its dependency classes inside, but I got java.lang.IllegalStateException: Failed to load ApplicationContext. Error creating bean with name 'emailSenderService. No qualifying bean of type 'org.springframework.mail.javamail.JavaMailSender' available: expected at least 1 bean which qualifies as autowire candidate.'.
Do I must have to run the whole application to test a single service?
build.yml
{
testImplementation ('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'junit', module: 'junit'
}
testImplementation "org.junit.jupiter:junit-jupiter:5.4.1"
}
Service:
public class EmailSenderService {
private final JavaMailSender sender;
private final SpringTemplateEngine templateEngine;
private final MessageSource i18n;
public EmailSenderService(JavaMailSender sender, SpringTemplateEngine templateEngine,
#Qualifier("messageSource") MessageSource i18n) {
this.sender = sender;
this.templateEngine = templateEngine;
this.i18n = i18n;
}
}
test class:
#SpringBootTest(
classes = {EmailSenderService.class}
)
#ExtendWith({SpringExtension.class})
class EmailServiceTest {
private static GreenMail smtp;
#Autowired
private EmailSenderService mailService;
#BeforeAll
static void init() {
smtp = new GreenMail(new ServerSetup(3026,null,"smtp"));
smtp.start();
}
#AfterAll
static void tearDown() {
smtp.stop();
}
#BeforeEach
void clearUp() throws FolderException {
smtp.purgeEmailFromAllMailboxes();
}
#Test
void testNewBidRequestEmail() throws MessagingException {
EmailMessageTemplateDto contact = new EmailMessageTemplateDto("test","test#test.com","test message");
mailService.sendUserContactEmail(contact);
Assertions.assertTrue(smtp.waitForIncomingEmail(1));
}
}
Error:
2019-04-03 14:56:06.146 WARN 732 --- [ main]
o.s.w.c.s.GenericWebApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'emailSenderService': Unsatisfied
dependency expressed through constructor parameter 0; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.mail.javamail.JavaMailSender' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations: {} 2019-04-03 14:56:06.153 ERROR 732 --- [
main] o.s.b.d.LoggingFailureAnalysisReporter :
*************************** APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in
com.server.server.service.EmailSenderService required a bean of
type 'org.springframework.mail.javamail.JavaMailSender' that could not
be found.
Action:
Consider defining a bean of type
'org.springframework.mail.javamail.JavaMailSender' in your
configuration.
2019-04-03 14:56:06.159 ERROR 732 --- [ main]
o.s.test.context.TestContextManager : Caught exception while
allowing TestExecutionListener
[org.springframework.test.context.web.ServletTestExecutionListener#342c38f8]
to prepare test instance
[com.server.server.test.junit.EmailServiceTest#4c7a078]
java.lang.IllegalStateException: Failed to load ApplicationContext at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
~[spring-test-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
...
The problem is that you really don't have a JavaMailSender available (and you wouldn't want a real one during your tests). You have four options:
Register a mock/stub JavaMailSender bean in a test configuration.
Use auto-configuration to make your EmailSenderService itself #ConditionalOnBean(JavaMailSender.class) and register a stub if there isn't one (this is usually what I do for testing "does the system send transactional mail?").
In this case, since you're actually trying to test the EmailSenderService itself, set spring.mail.host: localhost in your application-test properties (or an annotation).
Don't use Spring DI at all here. The major advantage of constructor injection is that you can hand-instantiate your beans, and you could new up your EmailSenderService and its dependencies.
If I understand the intended scope of your test, #3 is probably the solution to go with for you.
I currently have a Spring Boot application with a dependency to a Java module. This Java module has some classpath properties. When I #Autowired a bean from the Java module in my Spring Boot application and define this bean with a #Bean annotation and then run the Spring Boot application it will throw errors.
Error thrown:
2017-02-07 12:16:03.188 WARN 17620 --- [on(4)-127.0.0.1] ationConfigEmbeddedWebApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MyService': Unsatisfied dependency expressed through method 'setClassPathProperty' parameter 0; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'myClassPathProperties' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
Property defined in Java Module
src/main/resources/myproject-context.xml
<util:properties id="myClassPathProperties" location="classpath:myproject.properties" />
Property usage in Java Module
#Value("#{myClassPathProperties['property.x']}")
public void setClassPathProperty(String x) {
this.x = x;
}
Bean definition in Spring Boot application
#Bean (name = "mailSubscriptionDao")
public MyService getMyService() {
return new MyServiceImpl();
}
Try to get the whole properties object injected
#Autowired
Properties myClassPathProperties;
If this works, you know you have loaded myproject-context.xml correctly.
Than you can also have a look with the debugger, whether a property with name 'property.x' exists or not.
For spring boot + integration application, I'm attempting to load configuration from database, allow it to be accessible to Spring's Environment & inject-able via #Value annotation and be override-able by externalized configurations as described in the spring boot reference documentation under the Externalized Configuration Section.
The problem I'm having is that my spring Integration XML contains ${input} property placeholders that can not be resolved, because I can't get the database backed configuration to be loaded before Spring attempts to load the XML configurations.
The entry point to the application:
#SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
How database configuration would be loaded:
#Configuration
public class DbPropertiesConfig {
#Autowired
private org.springframework.core.env.Environment env;
#PostConstruct
public void initializeDatabasePropertySourceUsage() {
MutablePropertySources propertySources = ((ConfigurableEnvironment) env).getPropertySources();
try {
// The below code will be replace w/ code to load config from DB
Map<String,Object> map = new HashMap<>();
map.put("input-dir","target/input");
map.put("output-dir","target/output");
DbPropertySource dbPropertySource = new DbPropertySource("si",map);
propertySources.addLast(dbPropertySource);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
How Spring Integration config is loaded:
#Profile("IN")
#Configuration
#ImportResource({"si-common-context.xml","si-input-context.xml"})
public class SiInputAppConfig {
}
The Spring Integration XML configurationsi-input-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:int-file="http://www.springframework.org/schema/integration/file"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/file
http://www.springframework.org/schema/integration/file/spring-integration-file.xsd" default-lazy-init="true">
<int-file:inbound-channel-adapter channel="input2" directory="${input-dir}" filename-pattern="*">
<int:poller fixed-rate="500"/>
</int-file:inbound-channel-adapter>
<int:service-activator input-channel="input2" ref="sampleEndpoint" method="hello" output-channel="output2"/>
<int:channel id="output2"/>
<int-file:outbound-channel-adapter channel="output2" directory="${output-dir}"/>
</beans:beans>
The error I get:
2015-10-28 17:22:18.283 INFO 3816 --- [ main] o.s.b.f.xml.XmlBeanDefinitionReader : Loading XML bean definitions from class path resource [si-common-context.xml]
2015-10-28 17:22:18.383 INFO 3816 --- [ main] o.s.b.f.xml.XmlBeanDefinitionReader : Loading XML bean definitions from class path resource [si-mail-in-context.xml]
2015-10-28 17:22:18.466 INFO 3816 --- [ main] o.s.b.f.config.PropertiesFactoryBean : Loading properties file from URL [jar:file:/C:/Users/xxx/.m2/repository/org/springframework/integration/spring-integration-core/4.1.6.RELEASE/spring-integration-core-4.1.6.RELEASE.jar!/META-INF/spring.integration.default.properties]
2015-10-28 17:22:18.471 INFO 3816 --- [ main] o.s.i.config.IntegrationRegistrar : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2015-10-28 17:22:18.604 INFO 3816 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; ...
2015-10-28 17:22:18.930 WARN 3816 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean#0.source' defined in null: Could not resolve placeholder 'si.in-input' in string value "${si.in-input}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'input-dir' in string value "${input-dir}" ...
Spring loads DbPropertiesConfig after XML configuration is attempted to be loaded.
How can I resolve this issue?
Thanks in advance
AP
Yes, I can confirm by my home tests that XML definitions are loaded before the annotation stuff. It's enough complicated to determine why it is, but I'm sure that #Import* resources are more important by premise than an internal #Configuration logic.
Therefore your #PostConstruct isn't good for mix with XML.
One solution is to move all Spring Integration configuration to the Annotation style and even consider to use Spring Integration Java DSL.
Another solution is to follow with Spring Boot's Externalized Configuration recommendation:
Default properties (specified using SpringApplication.setDefaultProperties).
That means you have to read properties from your DB before the starting Spring Application. Yes, if you were going to use DataSource on the matter from the same application, it won't be possible. From other side let's take a look to your goal one more time! You are going to load properties for the application from DB as an external configuration, so, what is the point to do that from the application itself? Of course, it would be more safe to load and feed properties before application start.
Hope I am clear.