Home > Software design >  Failed to get access of a spring container object using @Autowired annotation
Failed to get access of a spring container object using @Autowired annotation

Time:06-10

I am new to spring boot. I am trying to understand Dependency Injection. I created a @Component bean and try to get it's instance object into a simple POJO class.

Let's take a look at example:

// Planet.java
@Component
class Planet() {
   private Long planetId;
   private String planetName;
   
   // ... getter-setter and constructor
}

since Planet object is annotated with @Component so it will be created by spring context container. Now I have created a simple POJO class....

// Species.java
class Species() {
   private Long spId;
   private String spName;
   
   // I want to get the object of Planet from container
   @Autowired
   private Planet planet;

   // getter-setter and constructor
}

Now when I create my Species object with new keyword(new Species()) then...

  1. Planet Object is created by container as expected.
  2. But In my Species object planet property instead of referencing Planet object it reference to a null value (not expected)..

Since I am Autowiring planet property, it should get that object from container but It is not getting that object. Please let me know Where I am doing something wrong..

I also tried to create beans using @Configuaration but still it's not working..

CodePudding user response:

Spring can only autowire beans into others spring-managed beans. Species object here is unmanaged so it can't work.

If you really want to keep the control on species instances (I mean control the construction by yourself) you have to inject dependency by yourself. So recover the planet object up-front and then inject it into the constructor

Planet p = // Planet injection ;
new Species(planet);

You can also give up control and simply annotate Species with @Component (or a specialized version of it).

Last way via a config type.

@Configuration
public class Config {

@Autowired
private Planet p;

@Bean
public getSpecies() {
return new Species(p);
}
}

CodePudding user response:

Spring, as an IOC container, helps us manage beans, such as contructing, and injecting attribute values. In other words, Spring only helps us manage beans.

Objects generated by new operator are not beans and cannot be managed by Spring. Therefore, the DI capability of Spring cannot be obtained.

So, make Species as a bean and Spring will help us to do dependency injection. We can annotate Species with @Component(@Service, and so on), or write a method with @Bean to create Species.

  • Related