PostConstruct in inner Spring configuration not getting invoked - java

Im trying to setup multiple filter chains as follows in Spring Security and running into a weird issue.
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration {
#Configuration("apiWebSecurityConfigurationAdapter")
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
....
}
#Configuration("ssoWebSecurityConfigurerAdapter")
#Order(1)
public static class SSOWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private Timer backgroundTaskTimer;
private MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager;
#PostConstruct
public void init() {
this.backgroundTaskTimer = new Timer(true);
this.multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
}
#PreDestroy
public void destroy() {
this.backgroundTaskTimer.purge();
this.backgroundTaskTimer.cancel();
this.multiThreadedHttpConnectionManager.shutdown();
}
#Bean
#Qualifier("idp-test")
public ExtendedMetadataDelegate openiamExtendedMetadataProvider()
throws MetadataProviderException, ResourceException {
DefaultResourceLoader loader = new DefaultResourceLoader();
String metadataLocation = "classpath:/sso/idp-test.xml";
ResourceBackedMetadataProvider resourceBackedMetadataProvider =
new ResourceBackedMetadataProvider(backgroundTaskTimer,
new SpringResourceWrapperOpenSAMLResource(loader.getResource(metadataLocation.trim()))); // backgroundTaskTimer is null
resourceBackedMetadataProvider.setParserPool(parserPool());
ExtendedMetadataDelegate extendedMetadataDelegate =
new ExtendedMetadataDelegate(resourceBackedMetadataProvider, extendedMetadata());
extendedMetadataDelegate.setMetadataTrustCheck(true);
extendedMetadataDelegate.setMetadataRequireSignature(false);
backgroundTaskTimer.purge();
return extendedMetadataDelegate;
}
.....
}
}
It causes the error,
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.saml.metadata.ExtendedMetadataDelegate]: Circular reference involving containing bean 'ssoWebSecurityConfigurerAdapter' - consider declaring the factory method as static for independence from its containing instance. Factory method 'testExtendedMetadataProvider' threw exception; nested exception is java.lang.IllegalArgumentException: Task timer may not be null
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 114 common frames omitted
Caused by: java.lang.IllegalArgumentException: Task timer may not be null
at org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider.<init>(AbstractReloadingMetadataProvider.java:105)
at org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider.<init>(ResourceBackedMetadataProvider.java:76)
Why doesnt backgroundTaskTimer in the above case get set inside the PostConstruct ?

Related

Issues with test execution with #ConfigurationProperties usage in java sbring-boot application

Context is getting passed as null, hence getting NullPointerException in context.getBean("abcRestTemplate", RestTemplate.class). What can be the issue for context to be null.
AuthnConfig.java
#Getter
#ConfigurationProperties(prefix = "authn")
#Configuration
public class AuthnConfig {
#Value("${endpoint}")
private String endpoint;
#Value("${client-svc.name}")
private String serviceClientId;
}
RestTemplateConfig.java
#Configuration
public class RestTemplateConfig {
private final AuthnConfig authnConfig;
#Autowired
public RestTemplateConfig(final AuthnConfig authnConfig) {
this.authnConfig = authnConfig;
}
#Bean(name = "abcRestTemplate"){
public RestTemplate abcRestTemplate() {
//authConfig.getEndpoint() etc....
}
}
}
RestTemplateConfigTest.java
#RunWith(SpringRunner.class)
#SpringBootTest
#ActiveProfiles("test")
public class RestTemplateConfigTest {
#Autowired
private RestTemplateConfig restTemplateConfig;
#Autowired
private ApplicationContext context;
#Mock
private AuthnConfig authnConfig;
#Before
public void initializeConfig() {
Mockito.when(authnConfig.getEndpoint()).thenReturn("https://localhost");
}
#Test
public void testForBeanCreation() {
RestTemplate abcRestTemplate = context.getBean("abcRestTemplate", RestTemplate.class);
assertNotNull(abcRestTemplate);
}
}
Errors If #RunWith(MockitoJUnitRunner.class) is used in RestTemplateConfigTest.class:
java.lang.NullPointerException, context is getting passed as NULL in context.getBean("abcRestTemplate", RestTemplate.class);
Errors If #RunWith(SpringRunner.class) is used in RestTemplateConfigTest.class
[ERROR] testForBeanCreation Time elapsed: 0.028 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authnConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'endpoint' in value "${endpoint}"
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'endpoint' in value "${endpoint}"
You need to add the your SpringBooltApplication.class to this #SpringBootTest Annotation, just like this: #SpringBootTest(classes = SpringBootApplicationDemo.class)

Executors.newFixedThreadPool() returning null on Constructor instanced by #Bean

On my application I want centralize the control of threads, control the submit() tasks, count, activeCount and others informations about the thread pool. The tasks are submited all the time by many services on the application, so to see the metrics I want create a Scheduled job to print those informations periodically. Problem is returning null at the initialize application when create Executors.newFixedThreadPool().
Controll class
public class ThreadPoolWorkControl {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolWorkControl.class);
private ThreadPoolExecutor executor;
public ThreadPoolWorkControl() {
this.executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10); // NULL HERE (Caused by: java.lang.NullPointerException: null)
}
public int submitTask(Runnable task) {
executor.submit(task);
return executor.getQueue().size();
}
public ThreadPoolExecutor getExecutor() {
return this.executor;
}
}
Configuration
#Configuration
public class ThreadPoolWorkControlConfiguration {
#Bean
public ThreadPoolWorkControl threadPoolWorkControl() {
return new ThreadPoolWorkControl();
}
}
Job
#Component
#EnableScheduling
public class InfoThreadsJob {
private static final Logger LOGGER = LoggerFactory.getLogger(InfoThreadsJob.class);
#Autowired
ThreadPoolWorkControl threadPoolWorkControl;
#Scheduled(fixedDelay = 2000)
public void infosThreadPool() {
LOGGER.info("M=infosThreadPool, Msg=Active Size: {}, Pool Size: {}, Queue size: {}", threadPoolWorkControl.getExecutor().getActiveCount(), threadPoolWorkControl.getExecutor().getPoolSize(), threadPoolWorkControl.getExecutor().getQueue().size());
}
}
Errors:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'threadPoolWorkControl' defined in class path resource [.../configuration/ThreadPoolWorkControlConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [.../ThreadPoolWorkControl]: Factory method 'threadPoolWorkControl' threw exception; nested exception is java.lang.NullPointerException

coundn't get bean when running a jar packed from a springboot project

I can run my springboot project in IDEA nicely but when packed it to a jar and run with the java command, just got the java.lang.NullPointerException when getting a bean from spring context.
the first class which just got errors:
#Service
public class MdspiImpl extends CThostFtdcMdSpi {
public MdspiImpl(CThostFtdcMdApi mdapi) {
m_mdapi = mdapi;
logger.info("MdspiImpl is creating...");
***mdr = SpringContextUtil.getBean("marketDataRobot");//this is the error code***
}
}
the second class:
#Service
public class MarketDataRobot {
}
the SpringContextUtil class:
#Component("SpringContextUtil")
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
}
the gradle file:
jar {
baseName = 'programmingTrading'
version = '0.1.0'
manifest {
attributes 'Main-Class': 'com.blackHole.programmingTrading'
}
}
the running exception:
WARN main[AbstractApplicationContext.java:557 Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mdspiImpl' defined in URL [jar:file:/E:/workspace/simuPrd/programmingTrading-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/com/blackHole/programmingTrading/infrastructure/MdspiImpl.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.blackHole.programmingTrading.infrastructure.MdspiImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException]
[com.blackHole.programmingTrading.infrastructure.MdspiImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:300)
... 27 common frames omitted
Caused by: java.lang.NullPointerException: null
at com.blackHole.programmingTrading.SpringContextUtil.getBean(SpringContextUtil.java:35)
at com.blackHole.programmingTrading.infrastructure.MdspiImpl.<init>(MdspiImpl.java:46)
It also stem from another problem: #Autowired annotation doesn't work...
when using like this:
#Component
public class Scu{
}
in another class:
#Autowired
private Scu scu;
logger.info(String.format("MdspiImpl is creating...[%s]", scu.toString()));
will get a java.lang.NullPointerException: null
spring-boot configuration like this:
#SpringBootApplication
public class ProgrammingTrading {
public static void main(String[] args) {
SpringApplication.run(ProgrammingTrading.class, args);
}
}
that is part of reasons of using SpringContextUtil to get the bean...
thanks a lot!
SpringContextUtil shouldn't be a accessed statically like you are doing... Since you define it as a #Component do the following;
#Service
public class MdspiImpl extends CThostFtdcMdSpi {
#Autowired
private SpringContextUtil springContextUtil;
public MdspiImpl(CThostFtdcMdApi mdapi) {
m_mdapi = mdapi;
logger.info("MdspiImpl is creating...");
***mdr = springContextUtil.getBean("marketDataRobot");
}
}
Due to SpringContextUtil not being injected via Spring, but simply accessed statically, the applicationContext inside of it is ignored and is null in your case.
Also remove the static modifier;
#Component
public class SpringContextUtil implements ApplicationContextAware {
private ApplicationContext applicationContext;
// include getter/setter for applicationContext as well
public <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
}
edit
The trouble from the latest example project;
#Service
public class ExampleService {
#Autowired
private Logger logger;
public ExampleService() {
this.logger=logger;
logger.info("Im working");
}
}
Here the Logger will be null, when the ExampleService constructor is triggered, since the constructor is called before the injection starts, but you can merge this behaviour if you incorporate the injection through the said constructor as follows;
#Service
public class ExampleService {
private final Logger logger;
public ExampleService(Logger logger) {
this.logger = logger;
logger.info("Im working");
}
}
Works perfectly without any trouble...
You should never be accessing beans programmatically like you did with this SpringContextUtil, just inject MarketDataRobot in the constructor of MdspiImpl and you’re good to go (since it’s annotated with #Service). The preferred way is to use constructor injection instead of field injection, which will make it easier for you to write unit tests. You can also get rid of #Autowired if you have only one constructor.

Akka actors fails to initialize

I have simple application with Spring Boot + Akka. Rarely application fails to start with error message pointing to actor creation:
<!-- language-all: java -->
akka.actor.ActorInitializationException: akka://AkkaSystem/user/MyActor: exception during creation
I have following configuration of Spring and Akka:
Actor class
#Scope(SCOPE_PROTOTYPE)
#Component("MyActor")
public class MyActor extends UntypedActor {
....
}
SpringActorProducer class
public class SpringActorProducer implements IndirectActorProducer {
final ApplicationContext applicationContext;
final String actorBeanName;
public SpringActorProducer(ApplicationContext applicationContext,
String actorBeanName) {
this.applicationContext = applicationContext;
this.actorBeanName = actorBeanName;
}
#Override
public Actor produce() {
return (Actor) applicationContext.getBean(actorBeanName);
}
#Override
public Class<? extends Actor> actorClass() {
return (Class<? extends Actor>) applicationContext.getType(actorBeanName);
}
}
AkkaSpringExtension class
#Component
public class AkkaSpringExtension implements Extension {
private ApplicationContext applicationContext;
public void initialize(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public Props props(String actorBeanName) {
return Props.create(SpringActorProducer.class, applicationContext, actorBeanName);
}
}
and configuration class
#Configuration
public class AkkaConfiguration {
#Autowired
private ApplicationContext applicationContext;
#Autowired
private AkkaSpringExtension springExtension;
#Bean
public ActorSystem actorSystem() {
ExecutorService executor = Executors.newCachedThreadPool();
DelegatingSecurityContextExecutorService executorService = new DelegatingSecurityContextExecutorService(executor);
ExecutionContext ec = ExecutionContexts.fromExecutorService(executorService);
ActorSystem system = ActorSystem.create("AkkaSystem", customAkkaConfiguration(), this.getClass().getClassLoader(), ec);
springExtension.initialize(applicationContext);
return system;
}
#Bean
public Config customAkkaConfiguration() {
return ConfigFactory.load();
}
}
After that I'm creating an actor in body of my service:
private ActorRef myActor;
#Autowired
private ActorSystem actorSystem;
#Autowired
private AkkaSpringExtension springExtension;
public void afterPropertiesSet() throws Exception {
myActor = actorSystem.actorOf(springExtension.props("MyActor"), "MyActor");
}
Usually all works as expected but sometimes an exception occurs (maybe 1 from 20 server startups):
MyActor[ERROR] [09/19/2016 10:14:07.705] [pool-3-thread-1] [akka://AkkaSystem/user/MyActor] Error creating bean with name 'MyActor': Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: About-to-be-created singleton instance implicitly appeared through the creation of the factory bean that its bean definition points to
akka.actor.ActorInitializationException: akka://AkkaSystem/user/MyActor: exception during creation
at akka.actor.ActorInitializationException$.apply(Actor.scala:174)
at akka.actor.ActorCell.create(ActorCell.scala:607)
at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:461)
at akka.actor.ActorCell.systemInvoke(ActorCell.scala:483)
at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:282)
at akka.dispatch.Mailbox.run(Mailbox.scala:223)
at org.springframework.security.concurrent.DelegatingSecurityContextRunnable.run(DelegatingSecurityContextRunnable.java:83)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1153)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.lang.Thread.run(Thread.java:785)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyActor': Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: About-to-be-created singleton instance implicitly appeared through the creation of the factory bean that its bean definition points to
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:355)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076)
at com.swissre.cih.configuration.akka.SpringActorProducer.produce(SpringActorProducer.java:17)
at akka.actor.Props.newActor(Props.scala:213)
at akka.actor.ActorCell.newActor(ActorCell.scala:562)
at akka.actor.ActorCell.create(ActorCell.scala:588)
... 8 more
Caused by: java.lang.IllegalStateException: About-to-be-created singleton instance implicitly appeared through the creation of the factory bean that its bean definition points to
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:378)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getSingletonFactoryBeanForTypeCheck(AbstractAutowireCapableBeanFactory.java:865)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryBean(AbstractAutowireCapableBeanFactory.java:796)
at org.springframework.beans.factory.support.AbstractBeanFactory.isTypeMatch(AbstractBeanFactory.java:544)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:449)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:425)
at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:220)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
... 18 more
Any ideas what can be wrong?
I moved actor initialization from afterPropertiesSet to a regular method, so actors will be initialized at first method call and initialization failure gone.

Read Spring boot property inside listener

My requirement is, I need to initialize some application resources when server is started in spring boot. In order to initialize those resources, I need bunch of properties. So, I have kept those properties in external property file and I am trying to read the properties in my custom listener when spring boot is started. The problem is, I could not get any property values in the listener. I am able to read them after application started without any issues. But, I need them inside listener while application is starting. I am getting below exceptions...How to resolve it. help me pls!
2015-08-20 02:58:59.585 ERROR 9376 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/shared] : Exception sending context initialized ev
ent to listener instance of class com.org.man.api.initializer.PropertyInitializerListener
java.lang.NoSuchMethodError: com.org.man.api.beans.property.ConfigProperties.getConfigNames()Ljava/util/List;
at com.org.man.api.beans.property.PropertyBeanParser.initializeConfigProperties(PropertyBeanParser.java:33)
at com.org.man.api.initializer.J2eeInitializer.getJ2eePresets(J2eeInitializer.java:79)
at com.org.man.api.initializer.J2eeInitializer.initialize(J2eeInitializer.java:36)
at com.org.man.api.initializer.PropertyInitializerListener.contextInitialized(PropertyInitializerListener.java:81)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
2015-08-20 02:58:59.592 ERROR 9376 --- [ost-startStop-1] o.apache.catalina.core.StandardContext : One or more listeners failed to start. F
ull details will be found in the appropriate container log file
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Fac
tory method 'viewControllerHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: The resources may not be ac
cessed if they are not currently started
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 23 common frames omitted
Caused by: java.lang.IllegalStateException: The resources may not be accessed if they are not currently started
at org.apache.catalina.webresources.StandardRoot.validate(StandardRoot.java:245)
at org.apache.catalina.webresources.StandardRoot.getResource(StandardRoot.java:212)
Listener code
public class PropertyInitializerListener implements ServletContextListener {
private static final String INITIALIZED = PropertyInitializerListener.class.getName() + ".INITIALIZED";
private J2eeInitializer initializer;
#Autowired
PropertyBeanParser parser;
public void contextDestroyed(ServletContextEvent event) {
if (initializer != null) {
initializer.terminate();
}
ServletContext context = event.getServletContext();
context.removeAttribute(FileSearcher.CONFIG_FILE_PROP);
}
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
if (context.getAttribute(INITIALIZED) != null) {
throw new IllegalStateException(
"Already initialized - " +
"check whether you have multiple <listener> definitions in your web.xml!");
}
ConfigBean presets = super.getPresets();
presets = parser.initializeConfigProperties();
SmapiDebug.setSaveMode(true);
SmapiDebug.info("contextInitialized");
PropertyBeanparser code
#Configuration
#EnableConfigurationProperties({ConfigProperties.class,LoggingProperties.class,
InstrumentationProperties.class,KeyeventProperties.class})
public class PropertyBeanParser {
#Autowired
private ConfigProperties configProperties;
#Autowired
private LoggingProperties loggingProperties;
#Autowired
private InstrumentationProperties instrumentationProperties;
#Autowired
private KeyeventProperties keyeventProperties;
public ConfigBean initializeConfigProperties(){
ConfigBean configBean = new ConfigBean();
try{
if(configProperties.getConfigNames()!=null && configProperties.getConfigValues()!=null) {
if(configProperties.getConfigNames().size()==configProperties.getConfigValues().size()){
for(int i=0;i<=configProperties.getConfigNames().size();i++){
ConfigVarDefinitionBean var = new ConfigVarDefinitionBean(configProperties.getConfigNames().get(i),
configProperties.getConfigValues().get(i));
configBean.addConfigVarDefinition(var);
}
}
else{
throw new Exception("number of names and values are not matching");
}
}
}
catch(Exception e){
e.getMessage();
}
return configBean;
}
}
ConfigProperties class
#Configuration
#ConfigurationProperties(locations = "file:config.properties", prefix = "config")
public class ConfigProperties {
private List<String> configNames = new ArrayList<String>();
private List<String> configValues = new ArrayList<String>();
public List<String> getConfigNames() {
return configNames;
}
public void setConfigNames(List<String> configNames) {
this.configNames = configNames;
}
public List<String> getConfigValues() {
return configValues;
}
public void setConfigValues(List<String> configValues) {
this.configValues = configValues;
}
}
Config.Properties
config.configNames[0]=test1
config.configNames[1]=Testserver
config.configNames[2]=ResourceId
config.configNames[3]=AdaptorName
config.configNames[4]=runLevel
config.configValues[0]=ServiceComp
config.configValues[1]=Test
config.configValues[2]=instance2
config.configValues[3]=test
config.configValues[4]=localhost
The issue is, properties can't be retrieved inside listener during spring boot start up. So, in order to do some initialization in the start up, we can add run method in the class where #SpringBootApplication annotation is set by implementing CommandLineRunner . If you do so, that run method will be executed just before finishing the SpringApplication's run method.This is how I tried.
#SpringBootApplication
public class SpringResource implements CommandLineRunner {
/**
* #param args
*/
#Autowired
PropertyTest test;
public void run(String... args){
test.print();
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringResource.class, args);
}
}
PropertyTest Class
#Configuration
#EnableConfigurationProperties({ConfigProperties.class})
#Controller
public class PropertyTest {
#Autowired
ConfigProperties config;
#RequestMapping(value = "/dummy", method = RequestMethod.GET)
#ResponseBody
public void print() {
// TODO Auto-generated method stub
for(int i=0;i<config.getConfigNames().size();i++)
System.out.println("Im in Property test method. :)" +config.getConfigNames().get(i)+" "+config.getConfigValues().get(i));
}
}
I'm answer from my mobile, but may the problem it's in the listener, you not autowire PropertyBeanparser you create, and you broke spring magic... I think in main app class springboot to declare a listener and make inside spring "flow" hope that help

Categories