2017-09-23 75 views
0

我想在应用程序启动期间(或者在结束时)执行一些代码。我使用@PostConstruct批注,@EventListener(ContextRefreshedEvent.class),实现了InitializingBean,实现了ApplicationListener,我发现了一些资源。它们都在启动时执行我的代码,但是应用程序属性的占位符不会被替换为时刻。所以如果我的类有一个具有@Value(“$ {my.property}”)注解的成员,它将返回“$ {my.property}”,而不是在yaml(或任何地方)中定义的实际值。 如何在更换发生后完成我的代码?在Spring启动时执行方法

+1

春天配置将解决放在'@ Value'内的财产的占位符。如果未加载,则表示不正确的属性名称,或者特定的yaml未加载到上下文中。当然你可以使用'@ PostConstuct'来设置会员 – Barath

回答

0

您可以实施InitializingBean,该方法的名称为afterPropertiesSet()。此方法将在所有属性占位符被替换后调用。

0

@PostConstruct在bean创建时被调用。 Ypu必须检查弹簧是否找到带有属性的文件。

+0

使用评论或编辑 –

0

如果你有一个配置类,@Configuration,那么你可以尝试明确导入您的属性文件中加入以下注释:你的配置类和后

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

任何其他非配置资源应加载@Value注释应该可以正常工作。

0

你应该实现ApplicationListener<ContextRefreshedEvent>这样的:

@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 
     } 
    }