0

I've read more topic about this problem but i haven't already found an answer... my problem is more general.. "ALL the bean are injected as null"

I have a class that is my 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;
    }
}

In my main class i load it:

private AnnotationConfigApplicationContext ctx;

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

new AnotherClass();
}

And now, Anotherclass is:

class AnotherClass {

  @Inject MessageSource messageSource;

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

In AnotherClass the messageSource variable that i have injected, is null.

I've also tried to place a break-point on MessageSource @Bean to check if this is called after new AnnotationConfigApplicationContext and it is. But messageSource variable is null.

Mistre83
  • 2,677
  • 6
  • 40
  • 77
  • Consider what `new AnotherClass();` does. – Sotirios Delimanolis Mar 26 '15 at 19:40
  • In my case, AnotherClass is a class that extends JFrame and i would like to use MessageSource to load the labels. I'm trying to read the post you told me but without success :( – Mistre83 Mar 26 '15 at 19:54
  • _The field annotated `@Autowired` is `null` because Spring doesn't know about the copy of [AnotherClass] that you created with `new` and didn't know to autowire it_ – Sotirios Delimanolis Mar 26 '15 at 19:55
  • The `AnotherClass` instance you created with `new` is not managed by Spring. How do you Spring to inject anything into it? – Sotirios Delimanolis Mar 26 '15 at 19:56
  • Ah.... sorry i'm fairly new about Spring... As i sayd, i would like to use the MessageSource in my interfaces (JFrame)to internationalize them and dont hardcore labels etc. For this pourpose, how i could do? I need to create them with a new.... I've tried to annotate my AnotherClass extensd JFrame with @Component as suggested in the other topic but still not working.... sorry if this is an stupid question but as said... i'm new to Spring :( – Mistre83 Mar 26 '15 at 20:05

0 Answers0