@PostConstruct

What is @PostConstruct?

--Initialization method --Object initialization part --Declare in the method to be executed separately to perform initialization work after object creation. --The init method with PostConstruct annotation is executed when WAS goes up.

merit

  1. The bean is not yet initialized when the constructor is called. (There are no inserted dependencies.) But by using @PostConstruct, you can check the dependency at the same time when the bean is initially naturalized.

  2. You can be assured that it will only run once in the bean life cycle. (** Because it is initialized only once when the bean is created when WAS goes up.) Therefore, ** PostConstruct annotation can be used to prevent the bean from being initialized many times. .. ** **

Applicable source

This is a part of the code I wrote when I was studying WebSocket.


@Slf4j
@RequiredArgsConstructor
@Service
public class ChatService {

    private final ObjectMapper objectMapper;
    private Map<String, ChatRoom> chatRooms;

    @PostConstruct
    private void init() {
        chatRooms = new LinkedHashMap<>();
    }

    public List<ChatRoom> findAllRoom() {
        return new ArrayList<>(chatRooms.values());
    }

    public ChatRoom findRoomById(String roomId) {
        return chatRooms.get(roomId);
    }

    public ChatRoom createRoom(String name) {
        String randomId = UUID.randomUUID().toString();
        ChatRoom chatRoom = ChatRoom.builder()
                .roomId(randomId)
                .name(name)
                .build();
        chatRooms.put(randomId, chatRoom);
        return chatRoom;
    }

    public <T> void sendMessage(WebSocketSession session, T message) {
        try {
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}

At the end

When I was looking at the sample code and materials, I often used it in a class with the Service annotation, but I have to look into it. ..

Recommended Posts

@PostConstruct