Arquillian: Getting WFLYEE0117: Field field cannot be set, on Singleton.START - java

I am trying to run an arquillian test, the test use a bean mapped with #Singleton and #Startup annotations, inside the singleton there are some cache Types from infinispan that are injected using #Resource(lookup = "JNDI"), the error only tells of the filds can't be set
I am sure that I missing something in my Test class, This is the code from the class and the bean.
#RunWith(Arquillian.class)
public class EJBsBeanTest {
private static SimpleDateFormat SDF_YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
private Libreta lib;
private Documento documento;
private Documento documentoAdmin;
private Documento documentoRol;
#Deployment
public static Archive<?> createTestArchive() {
File[] files = Maven.resolver().loadPomFromFile("pom.xml")
.importRuntimeDependencies().resolve().withTransitivity().asFile();
WebArchive myArchive = ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(ConfigurationBean.class,... )
.addAsLibraries(files)
.addAsWebInfResource("jboss-deployment-structure.xml", ArchivePaths.create("jboss-deployment-structure.xml"))
.addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("META-INF/beans.xml"));
return myArchive;
}
}
............
#Startup
#Singleton
public class ConfigurationBean {
private static final Logger logger = Logger.getLogger(ConfigurationBean.class.getName());
private static Properties props;
private static IOException ioerror;
public static final String CACHE_RUA_CEIP = "evaluacionRuaCeip";
#Resource(lookup = "java:jboss/datagrid-infinispan/container/backend-manager/cache/externos-cache")
private Cache<String, Object> cacheExternos;
#Resource(lookup = "java:jboss/datagrid-infinispan/container/shiro-container")
private CacheContainer basicCacheContainer;
#Resource(lookup = "java:jboss/datagrid-infinispan/container/backend-manager/cache/permisosapp-cache")
private Cache<String, Object> cachePermisosApp;
#PostConstruct
public void init() {
try {
props = new Properties();
props.load(ConfigurationBean.class.getClassLoader().getResourceAsStream("ftp.properties"));
cachePermisosApp.clear();
cacheExternos.clear();
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
}
}
public Cache<String, Object> getCacheExternos() {
return cacheExternos;
}
public Properties getProps() {
return props;
}
public CacheContainer getBasicCacheContainer() {
return basicCacheContainer;
}
public Cache<String, Object> getCachePermisosApp() {
return cachePermisosApp;
}
}
And this is the error:
org.jboss.arquillian.container.spi.client.container.DeploymentException:
Cannot deploy test.war: {"WFLYCTL0062: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-1" => {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"test.war\".component.ConfigurationBean.START" => "java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance
Caused by: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance
Caused by: javax.ejb.EJBException: java.lang.IllegalArgumentException: WFLYEE0117: Field cacheExternos cannot be set - object of class org.infinispan.cache.impl.EncoderCache loaded by ModuleClassLoader for Module \"org.infinispan.core:ispn-9.4\" version 9.4.3.Final from local module loader #7776ab (finder: local module finder #79179359 (roots: /jboss/modules,/jboss/modules/system/layers/base,/jboss/modules/system/add-ons/ispn)) is not assignable to interface org.infinispan.Cache loaded by ModuleClassLoader for Module \"deployment.test.war\" from Service Module Loader
Caused by: java.lang.IllegalArgumentException: WFLYEE0117: Field cacheExternos cannot be set - object of class org.infinispan.cache.impl.EncoderCache loaded by ModuleClassLoader for Module \"org.infinispan.core:ispn-9.4\" version 9.4.3.Final from local module loader #7776ab (finder: local module finder #79179359 (roots: /jboss/modules,/jboss/modules/system/layers/base,/jboss/modules/system/add-ons/ispn)) is not assignable to interface org.infinispan.Cache loaded by ModuleClassLoader for Module \"deployment.test.war\" from Service Module Loader"}}}}

Finally I found an answer, the application wasn't find the module org.infinispan.core:ispn-9.4 in the generated .war so I add the module to the jboss-deployment-structure.xml file to have access to the module.
Here is the src/test/resources/jboss-deployment-structure.xml
<jboss-deployment-structure>
<ear-subdeployments-isolated>false</ear-subdeployments-isolated>
<deployment>
<dependencies>
<module name="org.infinispan.core" slot="ispn-9.4"/>
</dependencies>
</deployment>
</jboss-deployment-structure>

Related

Invocation of init method failed; nested exception is java.lang.RuntimeException: Can't start redis server

I am using embedded Redis in our Webflux testcases using the following dependency in pom.xml file
<dependency>
<groupId>com.github.kstyrc</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.6</version>
</dependency>
And using below annotations for controllertest classes
#RunWith(SpringRunner.class)
#AutoConfigureWebTestClient(timeout = "36000000")
#WithMockUser
#TestPropertySource(locations = "classpath:application-test.properties")
#SpringBootTest(classes = Application.class)
#DirtiesContext
When I run individual controllertest class, all the controllertest are passing.
When I start both the controllertest classes, one controllertest class is failing with following error:
Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embededRedis': Invocation of init method failed; nested exception is java.lang.RuntimeException: Can't start redis server. Check logs for details.
Below is the embedded Redis class I am using in my JUnit test
#Component
public class EmbededRedis {
#Value("${spring.redis.port}")
private int redisPort;
private RedisServer redisServer;
#PostConstruct
public void startRedis() throws IOException {
if(redisServer==null||!redisServer.isActive()) {
redisServer = new RedisServer(redisPort);
redisServer.start();
}
}
#PreDestroy
public void stopRedis() {
if(redisServer!=null) {
redisServer.stop();
}
}
}
Check if Redis port is available or not. if not, try to assign a different port
#Component
public class EmbededRedis {
#Value("${spring.redis.port:9999}")
private int redisPort;
private RedisServer redisServer;
#PostConstruct
public void startRedis() throws IOException {
if(redisServer==null||!redisServer.isActive()) {
redisServer = new RedisServer(redisPort);
redisServer.start();
}
}
#PreDestroy
public void stopRedis() {
if(redisServer!=null) {
redisServer.stop();
}
}
}
This issue got resolved after restarting the system

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.

Application fails to start when additional port is opened through an autoconfig as a module

I am trying to create a library which can enable exposing a SpringBoot app on a second port (8090).
For this to work I have an AutoConfiguration as defined below:
#Configuration
#ConditionalOnWebApplication(
type = Type.SERVLET
)
public class HttpConfig {
public HttpConfig() {
}
#Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addAdditionalTomcatConnectors(new Connector[]{this.createStanderConnecter()});
return factory;
}
private Connector createStanderConnecter() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(8090);
return connector;
}
}
If I define this configuration in the same project, it works just fine.
But if I import this config as a module, my application fails to start with following error:
Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans : tomcatServletWebServerFactory,servletContainer
What am I missing?
I figured. If someone else wants to accomplish what I am trying to do. Instead of the configuration, I had to implement WebServerFactoryCustomizer as follows:
#Component
#ConditionalOnWebApplication(
type = Type.SERVLET
)
public class HttpConfig implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
#Autowired
ApplicationContext context;
public HttpConfig() {
}
public void customize(TomcatServletWebServerFactory factory) {
factory.addAdditionalTomcatConnectors(new Connector[]{this.createStanderConnecter()});
}
private Connector createStanderConnecter() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(8090);
return connector;
}
}

How to disable autoconfiguration for undertow

I have a normal spring-boot web application using spring-boot-starter-web, i.e. an embedded tomcat.
Now one of the libraries I'm using for testing comes with undertow as a dependency (because it itself is starting an embedded webserver for mocking an external dependency), and this seems to get the spring-boot autoconfiguration to try to configure undertow as the embedded web server (which seems to break due to version mismatches, and is also not what I want – I'm fine with tomcat as my server).
Here is our test class:
package org.zalando.nakadiproducer.tests;
[... imports skipped ...]
import static io.restassured.RestAssured.given;
#RunWith(SpringRunner.class)
#SpringBootTest(
// This line looks like that by intention: We want to test that the MockNakadiPublishingClient will be picked up
// by our starter *even if* it has been defined *after* the application itself. This has been a problem until
// this commit.
classes = { Application.class, MockNakadiConfig.class },
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
//#EnableAutoConfiguration(exclude=EmbeddedWebServerFactoryCustomizerAutoConfiguration.class)
public class ApplicationIT {
#LocalManagementPort
private int localManagementPort;
#ClassRule
public static final EnvironmentVariables environmentVariables
= new EnvironmentVariables();
#BeforeClass
public static void fakeCredentialsDir() {
environmentVariables.set("CREDENTIALS_DIR", new File("src/main/test/tokens").getAbsolutePath());
}
#Test
public void shouldSuccessfullyStartAndSnapshotCanBeTriggered() {
given().baseUri("http://localhost:" + localManagementPort).contentType("application/json")
.when().post("/actuator/snapshot-event-creation/eventtype")
.then().statusCode(204);
}
}
With the main application class:
package org.zalando.nakadiproducer.tests;
[imports skipped]
#EnableAutoConfiguration
#EnableNakadiProducer
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
#Bean
#Primary
public DataSource dataSource() throws IOException {
return embeddedPostgres().getPostgresDatabase();
}
#Bean
public EmbeddedPostgres embeddedPostgres() throws IOException {
return EmbeddedPostgres.start();
}
#Bean
public SnapshotEventGenerator snapshotEventGenerator() {
return new SimpleSnapshotEventGenerator("eventtype", (withIdGreaterThan, filter) -> {
if (withIdGreaterThan == null) {
return Collections.singletonList(new Snapshot("1", "foo", filter));
} else if (withIdGreaterThan.equals("1")) {
return Collections.singletonList(new Snapshot("2", "foo", filter));
} else {
return new ArrayList<>();
}
});
// Todo: Test that some events arrive at a local nakadi mock
}
}
This is the error message:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowWebServerFactoryCustomizer' defined in class path resource [org/springframework/boot/autoconfigure/web/embedded/EmbeddedWebServerFactoryCustomizerAutoConfiguration$UndertowWebServerFactoryCustomizerConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer] from ClassLoader [sun.misc.Launcher$AppClassLoader#378fd1ac]
The mentioned definition class is in spring-boot-autoconfigure 2.0.3.RELEASE, and looks like this:
#Configuration
#EnableConfigurationProperties(ServerProperties.class)
public class EmbeddedWebServerFactoryCustomizerAutoConfiguration {
#ConditionalOnClass({ Tomcat.class, UpgradeProtocol.class })
public static class TomcatWebServerFactoryCustomizerConfiguration {
// tomcat, jetty
/**
* Nested configuration if Undertow is being used.
*/
#Configuration
#ConditionalOnClass({ Undertow.class, SslClientAuthMode.class })
public static class UndertowWebServerFactoryCustomizerConfiguration {
#Bean
public UndertowWebServerFactoryCustomizer undertowWebServerFactoryCustomizer(
Environment environment, ServerProperties serverProperties) {
return new UndertowWebServerFactoryCustomizer(environment, serverProperties);
}
}
}
How can I tell spring-boot to not configure Undertow?
I tried #EnableAutoConfiguration(exclude=EmbeddedWebServerFactoryCustomizerAutoConfiguration.class) on my test class (beside #SpringBootTest), but that has no effect.
If I try #EnableAutoConfiguration(exclude=EmbeddedWebServerFactoryCustomizerAutoConfiguration.UndertowWebServerFactoryCustomizerConfiguration.class), I get this error:
Caused by: java.lang.IllegalStateException: The following classes could not be excluded because they are not auto-configuration classes:
- org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$UndertowWebServerFactoryCustomizerConfiguration
Removing Undertow from your project's dependencies is the safest way. Spring Boot is based on classpath scanning so once Undertow is gone from the classpath it's auto-configuration won't be processed.
The problem with EmbeddedWebServerFactoryCustomizerAutoConfiguration is that it doesn't provide a property switch. It's purely based on servlet container class presence. To get rid of it, you would have to exclude the entire EmbeddedWebServerFactoryCustomizerAutoConfiguration:
#EnableAutoConfiguration(exclude=EmbeddedWebServerFactoryCustomizerAutoConfiguration.class)
public MyTest {
}
and in your test configuration define just the beans for starting Tomcat:
#TestConfiguraton
#EnableConfigurationProperties(ServerProperties.class)
public MyTestConfig {
#Bean
public TomcatWebServerFactoryCustomizer tomcatWebServerFactoryCustomizer(Environment environment, ServerProperties serverProperties) {
return new TomcatWebServerFactoryCustomizer(environment, serverProperties);
}
}

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