Spring Boot 시작 후
spring-boot 앱이 디렉토리의 변경을 감시하기 시작한 후에 코드를 실행하고 싶다.
만, 「 」는 「 」입니다.@Autowired
이 시점에서는 서비스가 설정되지 않았습니다.
★★★★★★★★를 찾을 수 .ApplicationPreparedEvent
@Autowired
주석이 설정됩니다.응용 프로그램이 http 요청을 처리할 준비가 되면 이벤트가 실행되도록 하는 것이 이상적입니다.
응용 프로그램이 스프링 부트로 가동된 후 코드를 실행하는 데 더 좋은 이벤트 또는 더 좋은 방법이 있습니까?
이것은 다음과 같이 간단합니다.
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
System.out.println("hello world, I have just started up");
}
「」에서 완료.1.5.1.RELEASE
시험:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {
@SuppressWarnings("resource")
public static void main(final String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
context.getBean(Table.class).fillWithTestdata(); // <-- here
}
}
Application Ready Event를 사용해 보셨습니까?
@Component
public class ApplicationStartup
implements ApplicationListener<ApplicationReadyEvent> {
/**
* This event is executed as late as conceivably possible to indicate that
* the application is ready to service requests.
*/
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
// here your code ...
return;
}
}
코드명 : http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/
이 메뉴얼에서는, 기동 이벤트에 대해 다음과 같이 기술하고 있습니다.
...
응용 프로그램 이벤트는 응용 프로그램 실행 시 다음 순서로 전송됩니다.
ApplicationStartedEvent는 실행 시작 시 전송되지만 리스너 및 이니셜라이저 등록을 제외한 처리 전에 전송됩니다.
컨텍스트에서 사용할 환경이 알려진 경우 컨텍스트가 생성되기 전에 ApplicationEnvironmentPreparedEvent가 전송됩니다.
ApplicationPreparedEvent는 새로고침이 시작되기 직전에 bean 정의가 로드된 후에 전송됩니다.
ApplicationReadyEvent는 새로고침 및 관련된 콜백이 처리된 후 응용 프로그램이 요청을 처리할 준비가 되었음을 나타내기 위해 전송됩니다.
기동시에 예외가 있는 경우는, Application Failed Event 가 송신됩니다.
...
초기화시에 모니터를 기동하는 빈을 작성하는 것만으로, 다음과 같은 것을 실현할 수 있습니다.
@Component
public class Monitor {
@Autowired private SomeService service
@PostConstruct
public void init(){
// start your monitoring in here
}
}
init
bean에 대한 자동 배선이 완료될 때까지 메서드가 호출되지 않습니다.
는 '스프링 부츠'를합니다.CommandLineRunner
그런 종류의 콩만 넣으면 됩니다.4.11.2에는 Spring 4.1(Boot 1.2)도.SmartInitializingBean
모든 것이 초기화된 후에 콜백을 받습니다. ★★★★★★★★★★★★★★★★★★★★★★.SmartLifecycle
(3번)
를 사용하여 클래스를 확장할 수 있습니다.run()
합니다.
import org.springframework.boot.ApplicationRunner;
@Component
public class ServerInitializer implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
//code goes here
}
}
ApplicationReadyEvent
는, 실행하는 태스크가 올바른 서버 조작의 요건이 아닌 경우에만 유효합니다.비동기 작업을 시작하여 변경 사항을 모니터링하는 것이 좋은 예입니다.
가 '않음''준비되지 않음'을 구현하는 SmartInitializingSingleton
REST 포트가 열리고 서버가 업무용으로 개방되기 전에 콜백을 받을 수 있기 때문입니다.
사용의 유혹에 빠지지 마세요.@PostConstruct
한 번만 일어나면 안 되는 태스크에 사용할 수 있습니다.여러 번 불린 걸 알면 깜짝 놀랄 거야
사용하다SmartInitializingSingleton
콩 > 4.> 4.1
@Bean
public SmartInitializingSingleton importProcessor() {
return () -> {
doStuff();
};
}
수단으로서 「」를 사용합니다.CommandLineRunner
은 콩으로 을 달 수 .@PostConstruct
.
Spring Boot 응용 프로그램 시작 후 코드 블록을 실행하는 가장 좋은 방법은 PostConstruct 주석을 사용하는 것입니다.또는 명령줄 주자를 동일한 용도로 사용할 수도 있습니다.
1. PostConstruct 주석 사용
@Configuration
public class InitialDataConfiguration {
@PostConstruct
public void postConstruct() {
System.out.println("Started after Spring boot application !");
}
}
2. 명령줄 러너빈 사용
@Configuration
public class InitialDataConfiguration {
@Bean
CommandLineRunner runner() {
return args -> {
System.out.println("CommandLineRunner running in the UnsplashApplication class...");
};
}
}
Dave Syer의 답변에 대한 예를 제시하면 다음과 같은 효과가 있습니다.
@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);
@Override
public void run(String...args) throws Exception {
logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args));
}
}
마음에 듭니다.EventListener
@cahen(매우 깨끗하기 때문에 https://stackoverflow.com/a/44923402/9122660))에 의한 주석입니다.아쉽게도 Spring + Kotlin 설정에서는 동작하지 않았습니다.Kotlin에서 기능하는 것은 클래스를 메서드 파라미터로 추가하는 것입니다.
@EventListener
fun doSomethingAfterStartup(event: ApplicationReadyEvent) {
System.out.println("hello world, I have just started up");
}
이것을 시험해 보면, 애플리케이션 콘텍스트가 완전하게 기동했을 때에 코드가 실행됩니다.
@Component
public class OnStartServer implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
// EXECUTE YOUR CODE HERE
}
}
몇 가지 선택지가 있습니다.
「」를 사용합니다.CommandLineRunner
★★★★★★★★★★★★★★★★★」ApplicationRunner
콩 의 :
Spring Boot은 응용 프로그램 시작 프로세스가 끝날 무렵에 이러한 작업을 수행합니다. 「」는,CommandLineRunner
8을 사용한 8을 사용한 CommandLineRunner의 예를 나타냅니다.
@Bean
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World");
}
에 주의:args
스트링 스트링 스트링 스트링 스트링스트링 스트링 스트링 스트링 스트링 스트링 스트링 스트링 스트링.또한 이 인터페이스를 구현하여 스프링 컴포넌트로 정의할 수도 있습니다.
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Hello World");
}
}
.ApplicationRunner
더 나은 인수 관리가 필요한 경우.가 Application Runner를 합니다.ApplicationArguments
장장 、 관리리관관관 션스스스 。
합니다.CommandLineRunner
★★★★★★★★★★★★★★★★★」ApplicationRunner
을 콩@Order
★★★★
@Bean
@Order(1)
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World, Order 1");
}
@Bean
@Order(2)
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World, Order 2");
}
Spring Boot의 ContextRefreshedEvent 사용:
스프링 부츠이러한 이벤트는 응용 프로그램 시작 프로세스의 단계가 완료되었음을 나타냅니다., 그럼 이 노래를 수 요.ContextRefreshedEvent
커스텀 코드를 실행합니다.
@EventListener(ContextRefreshedEvent.class)
public void execute() {
if(alreadyDone) {
return;
}
System.out.println("hello world");
}
ContextRefreshedEvent
는 여러 번 공개됩니다.따라서 코드 실행이 이미 완료되었는지 여부를 반드시 확인하십시오.
spring boot 어플리케이션용 Command Line Runner를 구현하기만 하면 됩니다.실행 방법을 구현해야 합니다.
public classs SpringBootApplication implements CommandLineRunner{
@Override
public void run(String... arg0) throws Exception {
// write your logic here
}
}
@Component 를 사용할 수 있습니다.
@RequiredArgsConstructor
@Component
@Slf4j
public class BeerLoader implements CommandLineRunner {
//declare
@Override
public void run(String... args) throws Exception {
//some code here
}
CommandLineRunner 또는 ApplicationRunner를 사용하는 가장 좋은 방법: run() 메서드 CommandLineRunner는 문자열 배열을 받아들이고 ApplicationRunner는 ApplicationArugument를 받아들입니다.
스프링 부트는 응용 프로그램 부팅 시 run() 메서드를 호출하는 ApplicationRunner 인터페이스를 제공합니다.단, 콜백 메서드에 전달되는 raw String 인수 대신 ApplicationArguments 클래스의 인스턴스가 있습니다.
@Component
public class AppStartupRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
//some logic here
}
}
언급URL : https://stackoverflow.com/questions/27405713/running-code-after-spring-boot-starts
'source' 카테고리의 다른 글
vuelidate에서 검증 필드를 동적으로 설정하려면 어떻게 해야 합니까? (0) | 2022.08.19 |
---|---|
Python 인터프리터를 정적으로 컴파일하시겠습니까? (0) | 2022.08.19 |
vue.js에서 범위 외부 css를 수행하는 방법 (0) | 2022.08.19 |
CSS 속성(컬러)을 VueJS 변수로 설정 (0) | 2022.08.19 |
화살표 연산자 vs.도트 연산자 (0) | 2022.08.19 |