Spring- @ PostConstruct annotation

@PostConstruct annotation

@PostConstruct annotation Many people think that it is provided by Spring. In fact, Java's own annotations.

Explanation of the annotation in Java: @PostConstruct This annotation is used to modify a non-static void () method . The method modified by @PostConstruct will be run when the server loads the Servlet, and will only be executed once by the server. PostConstruct is executed after the constructor and before the init () method.

 

Usually we will use the @PostConstruct annotation in the Spring framework to execute the order of the annotation method in the entire Bean initialization:

Constructor-> @Autowired (Dependency Injection)-> @PostConstruct (Annotated Method)


@Configuration
public class BeanConfiguration {

    @Bean
    public ToyFactory toyFactory() {
        return new DefaultToyFactory();
    }

}

interface

public interface ToyFactory {
    Toy createToy();
}

Interface implementation class

package com.sixinshuier.Initialization.servive.impl;

import com.sixinshuier.Initialization.entity.Toy;
import com.sixinshuier.Initialization.servive.ToyFactory;

import javax.annotation.PostConstruct;

public class DefaultToyFactory implements ToyFactory {

    public DefaultToyFactory() {
        System.out.println("构造器...");
    }

    // 1. 基于 @PostConstruct 注解
    @PostConstruct
    public void init() {
        System.out.println("@PostConstruct : DefaultToyFactory 初始化中...");
    }

    @Override
    public Toy createToy() {
        Toy toy = new Toy();
        toy.setName("Football");
        toy.setSize("big");
        return toy;
    }
}

main

package com.sixinshuier.Initialization.main;

import com.sixinshuier.Initialization.config.BeanConfiguration;
import com.sixinshuier.Initialization.entity.Toy;
import com.sixinshuier.Initialization.servive.ToyFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class PostConstructTest {

    public static void main(String[] args) {
        // 创建BeanFactory
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册Configuration Class(配置类)
        applicationContext.register (BeanConfiguration. class );
         // Start the spring application context 
        applicationContext.refresh ();
         // Dependency search 
        ToyFactory toyFactory = applicationContext.getBean (ToyFactory. class ); 
        Toy toy = toyFactory.createToy (); 
        System.out. println ( "ToyName:" + toy.getName () + "ToySize:" + toy.getSize ());
         // Close the Spring application context 
        applicationContext.close (); 
    } 
}

Output result

Constructor ... 
@PostConstruct: DefaultToyFactory Initializing ... 
ToyName: Football ToySize: big

 

Reference: https://blog.csdn.net/qq360694660/article/details/82877222

 

Guess you like

Origin www.cnblogs.com/shix0909/p/12716449.html