How to use #ImportResource annotation import differrent enviroment config file - spring-boot

I'm trying to use #ImportResource annotation import on different environment config files like reported below:
#EnableFeignClients
#EnableAsync
#ImportResource(locations= {"classpath:${dev|sit}/service-applicationContext.xml","classpath:${dev|sit}/client-applicationContext.xml"})
public class DmrEsbService {
}
Or I'm trying to use other ways to import properties like spring.profiles.active=test, as I reported below:
#Value("${spring.profiles.active}")
public String env;
#Autowired
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
synchronized (lock) {
if (null == ESBClientFactory.applicationContext) {
String[] profiles = {"/profiles/" + env + "/client-applicationContext.xml", "/profiles/" + env + "/service-applicationContext.xml"};
ESBClientFactory.applicationContext = new ClassPathXmlApplicationContext(profiles, applicationContext);
}
}
}
but by using this last way to startup the app, it happened like below:
2021-12-10 15:04:16.005 - [<init> 122] - [INFO] - To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2021-12-10 15:04:16.027 - [getInstance 281] - [INFO] - DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration#1fdc92b
2021-12-10 15:04:17.795 - [refresh 554] - [WARN] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'publicQueryService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxxx.oracle.xmlns.apps.cux.soaprovider.plsql.cux_esb_mass_query_pkg.CUXESBMASSQUERYPKGPortType' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
2021-12-10 15:04:17.810 - [log 173] - [INFO] - Stopping service [Tomcat]
2021-12-10 15:04:17.917 - [logMessage 142] - [INFO] -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-12-10 15:04:17.917 - [deregister 65] - [INFO] - Unregistering application xxxx with eureka with status DOWN
2021-12-10 15:04:17.918 - [shutdown 888] - [INFO] - Shutting down DiscoveryClient ...
2021-12-10 15:04:17.925 - [shutdown 911] - [INFO] - Completed shut down of DiscoveryClient
2021-12-10 15:04:18.225 - [report 42] - [ERROR] -
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean of type 'com.xxx.oracle.xmlns.apps.cux.soaprovider.plsql.cux_esb_mass_query_pkg.xxx' that could not be found.
Action:
Consider defining a bean of type 'com.xxx.oracle.xmlns.apps.cux.soaprovider.plsql.cux_esb_mass_query_pkg.xxx' in your configuration.
I could not use the command below to package an app:
mvn clean -Dmaven.test.skip=true package -pl xxx -am -Psit
and then I'm using the following:
mvn clean install
could anyone who can tell to how to import different environment in my project?

Related

Field properties in org.springframework.cloud.netflix.turbine.stream.TurbineStreamAutoConfiguration required a bean of type

I went through links like: Spring Boot + Eureka Server + Hystrix with Turbine: empty turbine.stream, but still did not worked for me. This question is continuation of Unable to connect to Command Metric Stream. in Hystrix Dashboard issue.
My source code: https://github.com/javaHelper/spring-cloud-cordinating-services/tree/master/Protecting-Systems-with-Circuit-Breakers
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-01-15 10:46:04.141 ERROR 4380 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field properties in org.springframework.cloud.netflix.turbine.stream.TurbineStreamAutoConfiguration required a bean of type 'org.springframework.cloud.netflix.turbine.stream.TurbineStreamProperties' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.cloud.netflix.turbine.stream.TurbineStreamProperties' in your configuration.
Simply trying to start the
turbine::
TurbineApplication.java
#SpringBootApplication
#EnableTurbine
public class TurbineApplication {
public static void main(String[] args) {
SpringApplication.run(TurbineApplication.class, args);
}
}
application.properties
server.port=3000
spring.application.name=turbine-aggregator
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
turbine.app-config=weather-app,datetime-app
turbine.cluster-name-expression=new String("default")
remove the turbine stream dependencies from the pom.xml
That should resolve the problem.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-turbine-stream</artifactId>
</dependency>
Maybe you need to configure Spring to enable configuration properties for turbine?
#Configuration
#EnableConfigurationProperties(TurbineStreamProperties.class)
public class TurbineConfig {
}

Connect to Azure KeyVault using K8s ConfigMap and Spring Boot

I have a configmap created in my AKS with these properties
config-application-dev.properties: |
server.port=5001
server.compression.enabled=true
azure.keyvault.uri=<URL>
azure.keyvault.client-id=<CLIENTID>
azure.keyvault.client-key=<CLIENTKEY>
My Spring boot application read those properties using #PropertySource
#PropertySource({ "${propertiesDir}/${envTarget}/config/config-application-${envTarget}.properties" })
public class Application{
...
}
And I want to read the Key using #Value property
#Value("${azure-key-vault-secret}")
private String mySecretProperty;
But, when SpringBoot starts, It throws this error message ...
It can't resolve the placeholder ...
the connection to azure is not working ?
2019-08-21 16:17:26.051 WARN 1 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'exampleController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'secret-in-keyvault' in value "${secret-in-keyvault}"

Run Spring Boot Application With Dev Configuration Or Test Configuration

I have some multi-environment configurations.
The application.yml is like
spring:
profiles:
active: #profileActive#
The application-dev.yml is like
server:
port: 8085
spring:
application:
name: xxxx-info
datasource:
name: xxx-db
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://192.168.1.14:3306/xxx
username: root
password: *******
driver-class-name: com.mysql.jdbc.Driver
minIdle: 1
maxActive: 8
initialSize : 1
testWhileIdle: true
mybatis:
typeAliasesPackage: com.xxx.commons.common.entity
mapperLocations: classpath:mybatis/*.xml
And the application-test.yml is the same as application-dev.yml.
Application.java is like
#EnableDiscoveryClient
#SpringBootApplication
#EnableEurekaClient
#EnableFeignClients
#MapperScan("com.xxx.ggg.client.dao")
public class ClientInfoApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientInfoApplication.class);
public static void main(String[] args) {
SpringApplication.run(ClientInfoApplication.class, args);
}
}
Then I run spring boot application in IntelliJ
Here is the problem. Running spring boot application with application-test.yml is successful but not with application-dev.yml.
The logs are like
2018-12-17 14:27:23.497 [main][INFO]com.xxx.ggg.client.ClientInfoApplication[597]: The following profiles are active: dev
2018-12-17 14:27:24.490 [main][INFO]org.apache.coyote.http11.Http11NioProtocol[180]: Initializing ProtocolHandler ["http-nio-8080"]
2018-12-17 14:27:24.499 [main][INFO]org.apache.catalina.core.StandardService[180]: Starting service [Tomcat]
2018-12-17 14:27:24.500 [main][INFO]org.apache.catalina.core.StandardEngine[180]: Starting Servlet Engine: Apache Tomcat/8.5.31
2018-12-17 14:27:24.644 [localhost-startStop-1][INFO]org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/][180]: Initializing Spring embedded WebApplicationContext
2018-12-17 14:27:24.956 [main][WARN]org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext[551]: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientInfoRunner': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tagService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tagInfoDao' defined in file [D:\projects\ggg\client-info\target\classes\com\xxx\ggg\client\dao\TagInfoDao.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active).
2018-12-17 14:27:24.956 [main][INFO]org.apache.catalina.core.StandardService[180]: Stopping service [Tomcat]
2018-12-17 14:27:24.981 [main][ERROR]org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter[42]:
***************************
APPLICATION FAILED TO START
***************************
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active).

not able to autowire in spring boot

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-05-06 20:50:51.844 ERROR 2264 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field petRepo in com.pet.controller.PetController required a bean of type 'com.pet.repository.PetRepository' that could not be found.
Action:
Consider defining a bean of type 'com.pet.repository.PetRepository' in your configuration.
try adding #Repository annotation to your repo class
#Repository
public interface PetRepository <T,ID extends Serializable> extends CrudRepository{
}

#Autowired fails with JUnit & Spring

Really need help. I used JUnit(4.6) plus Spring(3.0.5) for unit testing. When I tried to autowire a service object in my test class, I got a NoSuchBeanDefinitionException.
The JUnit code:
package com.aaa.service.impl;
#ContextConfiguration(locations = { "classpath:/spring/applicationContext.xml",
"classpath:/spring/applicationContext-aop.xml",
"classpath:/spring/applicationContext-dao.xml",
"classpath:/spring/applicationContext-service.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
public class TestManageTargetServiceImpl {
#Autowired
ManageTargetServiceImpl manageTargetServiceImpl;
#Test
public void testQueryFinancialMonthList() {
List<Map<String, Object>> value = new ArrayList<Map<String, Object>>();
ManageTargetDao manageTargetDao = mock(ManageTargetDao.class);
when(manageTargetDao.queryFinancialMonthList()).thenReturn(value);
manageTargetServiceImpl.setManageTargetDao(manageTargetDao);
// I hope it return null
assertNull(manageTargetServiceImpl.queryFinancialMonthList());
}
}
The applicationContext-service.xml code:
<context:annotation-config />
<bean id="manageTargetService" class="com.aaa.service.impl.ManageTargetServiceImpl">
<property name="manageTargetDao" ref="manageTargetDao"></property>
</bean>
The error track:
00:51:28,625 ERROR main context.TestContextManager:324 - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#882dfc] to prepare test instance [com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.aaa.service.impl.TestManageTargetServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aaa.service.impl.ManageTargetServiceImpl com.aaa.service.impl.TestManageTargetServiceImpl.manageTargetServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.aaa.service.impl.ManageTargetServiceImpl] 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)}
Some log:
00:51:26,828 DEBUG main context.TestContextManager:282 - beforeTestClass(): class [class com.aaa.service.impl.TestManageTargetServiceImpl]
00:51:26,828 DEBUG main annotation.ProfileValueUtils:68 - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.aaa.service.impl.TestManageTargetServiceImpl]
00:51:26,828 DEBUG main annotation.ProfileValueUtils:80 - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.aaa.service.impl.TestManageTargetServiceImpl]
00:51:26,828 DEBUG main context.TestContextManager:315 - prepareTestInstance(): instance [com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0]
00:51:26,843 DEBUG main support.DependencyInjectionTestExecutionListener:73 - Performing dependency injection for test context [[TestContext#e0eb3f testClass = TestManageTargetServiceImpl, locations = array<String>['classpath:/spring/applicationContext.xml', 'classpath:/spring/applicationContext-aop.xml', 'classpath:/spring/applicationContext-dao.xml', 'classpath:/spring/applicationContext-service.xml'], testInstance = com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0, testMethod = [null], testException = [null]]].
00:51:26,843 DEBUG main support.AbstractGenericContextLoader:75 - Loading ApplicationContext for locations [classpath:/spring/applicationContext.xml,classpath:/spring/applicationContext-aop.xml,classpath:/spring/applicationContext-dao.xml,classpath:/spring/applicationContext-service.xml].
00:51:26,968 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext.xml]
00:51:27,187 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-aop.xml]
00:51:27,312 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-dao.xml]
00:51:27,421 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-service.xml]
00:51:27,453 INFO main support.GenericApplicationContext:456 - Refreshing org.springframework.context.support.GenericApplicationContext#16c14e7: startup date [Tue Jan 01 00:51:27 NZDT 2013]; root of context hierarchy
00:51:27,718 INFO main config.PropertyPlaceholderConfigurer:177 - Loading properties file from class path resource [jdbc.properties]
00:51:27,796 INFO main support.DefaultListableBeanFactory:555 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2938d8: defining beans [loggingAop,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,service,loginDao,manageTargetDao,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,txManager,txAdvice,txDAO,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,loginService,manageTargetService]; root of factory hierarchy
Guessing here - but given that injection of a class type ManageTargetServiceImpl is failing, I think the reason is that a proxy is getting created for ManageTargetServiceImpl and so the type of the bean will not be ManageTargetServiceImpl anymore but the interface of that class.
from Biju Kunjummen
Look at your property id. It should be manageTargetServiceImpl in your applicationContext-service.xml
Change it to this:
<bean id="manageTargetServiceImpl" class="com.aaa.service.impl.ManageTargetServiceImpl">
<property name="manageTargetDao" ref="manageTargetDao"></property>
</bean>

Resources