非WebApplication - Spring - @Inject MessageSource为null

时间:2015-03-26 19:36:19

标签: java spring

我已经阅读了关于这个问题的更多主题但我还没有找到答案......我的问题更为笼统......“所有bean都被注入为空

我有一个类是我的ApplicationContext:

@Configuration
public class AppContext {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = 
                new ReloadableResourceBundleMessageSource();
        //messageSource.setCacheSeconds(-1);
        messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
        messageSource.setBasenames("classpath:src/main/resources/i18n/messages", "classpath:src/main/resources/i18n/errors");
        return messageSource;
    }
}

在我的主要课程中我加载它:

private AnnotationConfigApplicationContext ctx;

public MyClassLoader() {
 this.ctx = new AnnotationConfigApplicationContext(AppContext.class);
 this.ctx.register(AppContext.class); // Only for test, nothing is changed

new AnotherClass();
}

现在,Anotherclass是:

class AnotherClass {

  @Inject MessageSource messageSource;

  public AnotherClass() {
    String s = this.messageSource.getMessage("settings.title", null, Locale.ITALIAN);
        System.out.println(s);
}

在AnotherClass中,我注入的messageSource变量为null。

我还尝试在MessageSource @Bean 上放置一个断点,以检查在新的AnnotationConfigApplicationContext 之后是否调用它并且它是但是messageSource变量为空。

0 个答案:

没有答案