2022-11-14
1. 방법
최초 실행하고 싶은 메서드를 우선적으로 만든 후 아래와 같이 코드를 작성한다.
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
@Component
@RequiredArgsConstructor
public class ServiceInit implements InitializingBean{
private final ServiceInitTest serviceInitTest; //자신이 사용하고자 하는 클래스를 작성
@Override
public void afterPropertiesSet() throws Exception {
init(); //메소드 최초 호출시키기
}
public void init() {
serviceInitTest.serviceInit(); //자신이 호출하고싶은 메소드
}
}
InitializingBean라는 클래스를 implements 해서 사용하는 것이다. 해당 클래스는 최초 스프링 부트가 실행이 될때 동작을 한다. 아래의 소스코드에서 확인할 수 있듯이 afterPropertiesSet() 메소드를 오버라이딩 하여 실행하고자 하는 메서드를 넣으면, 해당 메서드는 스프링 부트 최초 실행 시 동작하게 된다.
package org.springframework.beans.factory;
/**
* Interface to be implemented by beans that need to react once all their properties
* have been set by a {@link BeanFactory}: e.g. to perform custom initialization,
* or merely to check that all mandatory properties have been set.
*
* <p>An alternative to implementing {@code InitializingBean} is specifying a custom
* init method, for example in an XML bean definition. For a list of all bean
* lifecycle methods, see the {@link BeanFactory BeanFactory javadocs}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see DisposableBean
* @see org.springframework.beans.factory.config.BeanDefinition#getPropertyValues()
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#getInitMethodName()
*/
public interface InitializingBean {
/**
* Invoked by the containing {@code BeanFactory} after it has set all bean properties
* and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
* <p>This method allows the bean instance to perform validation of its overall
* configuration and final initialization when all bean properties have been set.
* @throws Exception in the event of misconfiguration (such as failure to set an
* essential property) or if initialization fails for any other reason
*/
void afterPropertiesSet() throws Exception;
}