It is possible to use a @Resource defined in the same class @Configuration

0

I have something like this:

The class Other needs an instance of MyBean so create the attribute and use it when I create the bean Other

@Configuration 
public SomeClass {

     @Resource 
     private MyBean b;

     @Autowired
     Environment env;

     @Bean
     public MyBean myBean() {
         MyBean b = new MyBean();
         b.foo(env.getProperty("mb"); // NPE
         return b;
     }

     @Bean 
     public Other other() {
         Other o = new Other(o);
         return o;
     }
}

But I throw NullPointerException when initializing the object myBean , I guess it's because the property env has not yet been injected at that point.

If I do not use the bean but call the method directly everything works fine.

@Configuration 
public SomeClass {

     @Autowired
     Environment env;

     @Bean
     public MyBean myBean() {
         MyBean b = new MyBean();
         b.foo(env.getProperty("mb"); // NPE
         return b;
     }

     @Bean 
     public Other other() {
         Other o = new Other(myBean());
         return o;
     }
}

Is it because I'm defining @Bean in the same @Configuration class?

    
asked by OscarRyz 20.02.2016 в 00:16
source

1 answer

2

When you have a class decorated as @Configuration , Spring will take the parameters of the methods as other beans defined in the context. In this case, you can send MyBean myBean as an argument and Spring will inject the appropriate bean. In case you have more than one definition for MyBean , it is necessary to place the annotation @Qualifier to the argument to specify the name of the bean that you want to inject.

For the code that you present, this would be the configuration to use:

@Configuration 
public SomeClass {

     @Autowired
     Environment env;

     @Bean
     public MyBean myBean() {
         MyBean b = new MyBean();
         b.foo(env.getProperty("mb");
         return b;
     }

     @Bean
     public Other other(@Qualifier("myBean") MyBean myBean) {
         Other o = new Other(myBean);
         return o;
     }
}
    
answered by 24.02.2016 / 04:56
source