0

i want to execute some code during (or rather at the end of) application startup. I found a couple of resources doing this using @PostConstruct annotation, @EventListener(ContextRefreshedEvent.class), implementing InitializingBean, implementing ApplicationListener... All of them execute my code at startup, but the placeholder of the application properties are not replaced at that moment. So if my class has a member with an @Value("${my.property}") annotation, it returns "${my.property}" instead of the actual value defined in the yaml (or wherever). How do i accomplish to execute my code after the replacement took place?

  • 1
    spring configurations will resolve the property placeholders placed inside `@Value`. if it is not getting loaded it either means incorrect property name or particular yaml is not loaded into the context. Ofcourse you can use `@PostConstuct` to set the member – Barath Sep 23 '17 at 17:15

5 Answers5

0

You can implement InitializingBean which has a method named afterPropertiesSet(). This method will be called after all properties placeholders are replaced.

zuckermanori
  • 1,675
  • 5
  • 22
  • 31
0

@PostConstruct is called when bean is created. Ypu have to check if spring found file with properties.

0

If you have a config class, @Configuration, then you can try explicitly importing your properties file by adding the following annotation:

@PropertySource("classpath:your-properties-file.properties")

Any other non-config resources should load after your config classes and your @Value annotations should work fine.

Max Bilbow
  • 110
  • 7
0

You should implement ApplicationListener<ContextRefreshedEvent> like this:

@Component
public class SpringContextListener implements ApplicationListener<ContextRefreshedEvent> {

        @Value("${my.property}")
        private String someVal;

        /**
         * // This logic will be executed after the application has loded
         */
        public void onApplicationEvent(ContextRefreshedEvent event) {
            // Some logic here
        }
    }
mad_fox
  • 3,030
  • 5
  • 31
  • 43
0

You can get it after spring boot start.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

@Component
@Order(0)
class ApplicationReadyInitializer implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    ResourceLoader resourceLoader;

    @Value("${my.property}")
    private String someVal;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // App was started. Do something
    }

}