0

I have an Spring app that needs to load files from resource folder to external ftp storage on startup. So applications is starting -> files are uploaded ->application starts successfully -> bean which is responsible for uploading is destroyed. The thing is I don't want to use something like @PostConsrtuct/init for some bean and have idle bean in my context which did his job on startup.

I don't want to use @EventListener that would listen on refresh context and runs logic because this listener would perform this uploading every context refresh even after startup.

My app is pure Spring app (not a Spring Boot), so I can't use CommandLineRunner/AppStartupRunner interfaces.

Is that possible to setup some bean that runs once method and dies ?

Alfred Moon
  • 147
  • 1
  • 11

2 Answers2

1

Well, I should check behaviour of CommandLineRunner in Spring App before posting question. It looks like CommandLineRunner perfectly working even not in the spring boot application. So CommandLineRunner perfectly fits all my needs.

Alfred Moon
  • 147
  • 1
  • 11
0

You can have your class implement InitializingBean and implement your logic in afterPropertiesSet()

Deleting the bean at runtime is not recommended, although it can be done.

@Component
public class ABean implements InitializingBean, ApplicationContextAware {


    private ApplicationContext context;

    @Autowired
    private AnyBean anyBean;

    @Override
    public void afterPropertiesSet() throws Exception {
       // code
       // at end destroy bean like 

       context.getAutowireCapableBeanFactory().destroyBean(this);
    }

    @Override
    public void setApplicationContext(ApplicationContext context)
        throws BeansException {
           this.context=context;
    }

}

Rami Del Toro
  • 1,130
  • 9
  • 24