Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[20220904] Spring @PostConstructor, @PreDestory #265

Open
JuHyun419 opened this issue Sep 4, 2022 · 0 comments
Open

[20220904] Spring @PostConstructor, @PreDestory #265

JuHyun419 opened this issue Sep 4, 2022 · 0 comments
Labels

Comments

@JuHyun419
Copy link
Owner

@PostConstructor

  • Bean이 초기화 된 후 단 한 번 호출
  • 생성자에선 의존성 주입이 이루어 지지 않기에 비슷한 작업을 할 때 사용
  • 또한 컨테이너 내에서 여러 번 호출될 수 있는 사항을 한 번 호출되는 것으로 보장함
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    /* 생성자에서는 주입이 안되어서 에러 발생 */
//    public UserService() {
//        User admin = new User("admin", "password1");
//        userRepository.save(admin);
//    }

    @PostConstruct
    private void init() {
        User admin = new User("admin", "password1");
        User normalUser = new User("user", "password2");
        userRepository.save(admin);
        userRepository.save(normalUser);
    }

}

@PreDestory

  • ApplicationContext에서 스프링의 Bean을 제거하기 전 한 번만 실행
  • 자원 해제, Close 처리 등을 할 때 사용
@PreDestroy
public void dataSourceDestroy() throws SQLException {
    rollbackUnCommittedTransaction();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant