Friday, November 28, 2014

Spring Gotchas

This list will grow as I experience more Gotchas
  1. Think twice before creating your own objects using new operator. When you create your own objects you are not getting them from spring context, annotations like @autowire are not going to work. Have a look here.

Thursday, November 27, 2014

Spring annotation @autowire not working

1 @Configuration
2 @PropertySource("classpath:rdap-integration.properties")
3 public class Application {
4
5 @Autowired
6 private Environment env;
7
8 public static void main(String[] args) {
9 SpringApplication.run(Application.class, args);
10 Application app = new Application();
11 app.doWork(args);
12 }
13
14 private void doWork(String[] args) {
15 String val = env.getProperty("key");
16 System.out.println("Value = " + val);
17  }
18 }

Above code throws a NullPointerException at line 15. The problem is variable env is not getting autowired and is null, hence we get NPE. The mistake in above code is that we are creating our own Application object at line 10, this app object is not from the spring context, so nothing would be autowired to it. The correct way to do it would be to get the app object from spring context and not create it. See the working code below.

8  public static void main(String[] args) {
9 ApplicationContext ctx = SpringApplication.run(Application.class, args);
10 Application app = ctx.getBean(Application.class);
11 app.doWork(args);
12 }

In Spring never go out of context :-)