What is and what is the @PostConstruct in java beans?

1

In a project / code I'm encountering this @PostConstruct tag and I do not really understand what works? Someone can explain to me what their function or purpose is. I would appreciate it very much.

    
asked by Absol 05.06.2017 в 19:17
source

3 answers

2

@PostConstruct The @PostConstruct annotation defines a method as the initialization method of a spring bean that is executed after the dependency injection is completed. @PostConstruct is the init-method annotation form that is an attribute of the bean tag. The @PostConstruct method is used to validate bean properties or to initialize any task. In our bean, there should be only one method annotated with @PostConstruct annotation. The method can not be static.

You can see the example that I put here Book.java

package com.concretepage;
import javax.annotation.PostConstruct;

public class Book {
  private String bookName;
  public Book(String bookName) {
    this.bookName = bookName; }

@PostConstruct
public void springPostConstruct() {
     System.out.println("---Do initialization task---");
     if(bookName != null) {
         System.out.println("bookName property initialized with the value:"+ bookName);
     }
}   
public String getBookName() {
    return bookName;
}

AppConfig.java

package com.concretepage;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration

public class AppConfig {
@Bean
public Book book(){
  return new Book ("Rama");
}
}
    
answered by 06.06.2017 / 10:51
source
3

Marks with @PostConstruct a method that you want to execute on a new instance of your EJB after the container has resolved all dependencies. The uses they have are many, in my case I use it to ensure that certain resources are available for the EJB before calling the business methods.

    
answered by 05.06.2017 в 20:07
0

It is a function that will be executed before all the others.

    
answered by 05.06.2017 в 20:34