Correct way of making a singleton a Spring bean

前端 未结 6 781
野性不改
野性不改 2020-12-08 03:12

I am converting a singleton to a Spring bean, so that if the singleton fails to initialize, then entire web application\'s spring context doesn\'t load properly.

Th

6条回答
  •  春和景丽
    2020-12-08 03:30

    To run code at startup (and fail on error) use one of the many ways to register startup events, e.g. see http://www.baeldung.com/running-setup-logic-on-startup-in-spring

    Example:

    @Component
    public class InitializingBeanExampleBean implements InitializingBean {
    
        private static final Logger LOG = Logger.getLogger(InitializingBeanExampleBean.class);
    
        @Autowired
        private Environment environment;
    
        @Override
        public void afterPropertiesSet() throws Exception {
            LOG.info(Arrays.asList(environment.getDefaultProfiles()));
        }
    }
    

提交回复
热议问题