Home > Blockchain >  How to call PostConstruct method when creating an object with new keyword
How to call PostConstruct method when creating an object with new keyword

Time:10-21

I have a class Banana which has a @PostConstruct method that I want to run after the class object is created. I am creating the object of this class using these calls

Cat cat = new Cat();
Banana b = new Banana(cat);

So from the logs I understand that this @PostConstruct method is not being called when the Banana object is being created. I think the way I have implemented is not the correct usage. Can someone guide me how do I correctly implement this as this is my first task on Java project with Spring Boot. I need that setup code to run after Banana object is created, so is there any other way apart from @PostConstruct

@Slf4j
public class Banana {
    public Banana(Cat cat) {
        this.cat = cat;
    }
    private Cat cat;

    @PostConstruct
    public void setup() {
        // some code
    }

    public void execute() {
        // some code
    }
}

CodePudding user response:

All the annotations honored by spring (@PostConstruct, @PreDestroy, @Autowired and many others) are applicable when the object is created by spring itself. In this case spring can analyze the class, handle the annotations, etc.

When you instantiate by yourself (new Banana()) - spring doesn't even know that your object exists and hence can't call any of its method, so you're forced doing it by yourself. So yes, in this case you will have to call the method annotated with @PostConstruct manually, which means that the @PostConstruct annotation is pretty useless can can be omitted at all.

CodePudding user response:

The @PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method will be invoked by a framework, only if a framework controls the creation of an object.

Since you instantiate Banana manually - you also have to call it manually.

  • Related