0

I am trying to use spring 4 too load properties and use them in the classes, but it I can't get it to work. This is not an MVC appication and the reported duplicatet does not give me any clue on my issue. Here is what I got in my test project:

The main class:

 public class Main {

    public static void main(String...args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        Tester t = new Tester();
        t.testBean();
    }
}

ApplicationConfig Class:

@Configuration
@ComponentScan(basePackages={"nl.foo.propertiestest"})
@PropertySource("application.properties")
public class ApplicationConfig {
//Spring framework will know what to do with this class

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

The Tester Ckass:

public class Tester {
    @Autowired
    Environment env;

     @Bean
     public void testBean() {
         System.out.println("testBean start");
         String a = env.getProperty("test");
         System.out.println("property = " + a);
         System.out.println("testBean e");
     }

}

The application.properties:

test=hello tester

The application gives a null pointer exception on tring a = env.getProperty("test"); but it seems to load the properties, as it gives an error when the properties file is not in the class path.

How do I get the property retrieved?

Ronald
  • 31
  • 4
  • This has nothing to do with MVC, it has to do with the fact that you created your `Tester` using **new**, so spring doesn't know how to autowire it. This is *exactly* the issue in the linked duplicate. – azurefrog Nov 05 '14 at 21:35
  • When I change the `Tester t = new Tester();` to `Tester t = (Tester) context.getBean(Tester.class);` it still does not work, I get `No qualifying bean of type [nl.foo.propertystest.Tester] is defined` – Ronald Nov 05 '14 at 21:53
  • Without seeing how your tester bean is defined in your application context, I can't speak to why you can't load your bean. That is, however, a different problem than this one, so you should probably post it as its own question if you can't figure it out. – azurefrog Nov 05 '14 at 21:57
  • After some more hours I found the solution, in Main class, change `Tester t = new Tester();` to `Tester t = context.getBean(Tester.class);`. In the ApplicationConfig class, add: `@Bean public Tester tester() { return new Tester(); }` and in the Tester class, remove the `@Bean`. And it all works! – Ronald Nov 09 '14 at 16:12

0 Answers0