Rajat Mishra
Rajat Mishra

Reputation: 384

Is the bean for the class @Configuration always null?

Assume that all files are in a package named tom.

A.java

@AllArgsConstructor
public class A {
    public int x;
}

Teztt.java

@Configuration
public class Teztt {
    @Bean
    public A getA() {
        return new A(56);
    }
    public void print() {
        System.out.println("Hello world");
    }
}

Tezt.java

public class Tezt {
    @Autowired
    public Teztt teztt;
}

Tezt.xml

<bean class="tom.Teztt" />
<bean id="idTezt" class="tom.Tezt" />

Runner.java

public class Runner {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("tom/Tezt.xml");
        Tezt t = (Tezt) context.getBean("idTezt");
        if(t.teztt == null) {
            System.out.println("NPE");
        }
    }
}

The output of above is NPE. My question is I want to get Object of Teztt having non-null value. Is there a way in Spring to do this thing or will it always be null. Please help.

Upvotes: 0

Views: 340

Answers (2)

ugo
ugo

Reputation: 284

Since class Tezt do not initialize its member "public Teztt teztt", there's no reason to have a not null teztt. Either initialize teztt element inside Textsz class, or add a method, such as init() and modify spring beans configuration in runtime environment. For example:

public class Tezt {
    @Autowired
    public Teztt teztt = new Teztt();
}

but this way it never stops.

Using init-method inside xml bean:

 public class Tezt {
     public void init() {
         this.teztt = new Tezt();
     }
 ...

and

<bean id="idTezt" class="tom.Tezt" init-method="init" />

but this stops after the second.

Upvotes: 1

NikNik
NikNik

Reputation: 2301

Edited: in your xml you need to insert:

<context:annotation-config/>

and you need to declare your bean:

@Configuration
public class Config{
    @Bean
    public Teztt getTeztt(){
      return new Teztt();
    }

    @Bean
    public A getA() {
        return new A(56);
    }
}

Upvotes: 1

Related Questions