Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the seven startup extension points left to developers by SpringBoot?

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the seven startup extension points left to developers by SpringBoot. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

We often need to do some hook actions when the container starts, such as registering the message consumer, listening to the configuration, and so on. Today, we will summarize the seven startup extension points left to developers by SpringBoot.

Container refresh completes extension point 1, listens to container refresh completes extension point ApplicationListener

Basic usage

Students who are familiar with Spring must know that successful container refresh means that all Bean initialization has been completed. When the container is refreshed, Spring will call all the onApplicationEvent methods in the container that implement ApplicationListener Bean, so that the application can listen for container initialization completion events.

@ Component public class StartupApplicationListenerExample implements ApplicationListener {private static final Logger LOG = Logger.getLogger (StartupApplicationListenerExample.class); public static int counter; @ Override public void onApplicationEvent (ContextRefreshedEvent event) {LOG.info ("Increment counter"); counter++;}}

Fallible point

This extension point needs extra attention when used in a web container. In a web project (such as spring mvc), there are two containers in the system, one is root application context, and the other is our own context (as a child of root application context). If you follow the above method, the onApplicationEvent method will be executed twice. The solution to this problem is as follows:

@ Component public class StartupApplicationListenerExample implements ApplicationListener {private static final Logger LOG = Logger.getLogger (StartupApplicationListenerExample.class); public static int counter; @ Override public void onApplicationEvent (ContextRefreshedEvent event) {if (event.getApplicationContext (). GetParent () = = null) {/ / root application context does not have parent LOG.info ("Increment counter"); counter++;}

High-level play

Of course, this extension can also be played at a higher level: custom events, you can use Spring to implement an observer mode at a minimum cost:

Customize an event first:

Public class NotifyEvent extends ApplicationEvent {private String email; private String content; public NotifyEvent (Object source) {super (source);} public NotifyEvent (Object source, String email, String content) {super (source); this.email = email; this.content = content;} / / omit getter/setter method}

Register an event listener

@ Component public class NotifyListener implements ApplicationListener {@ Override public void onApplicationEvent (NotifyEvent event) {System.out.println ("email address:" + event.getEmail ()); System.out.println ("email content:" + event.getContent ());}}

Publish event

@ RunWith (SpringRunner.class) @ SpringBootTest public class ListenerTest {@ Autowired private WebApplicationContext webApplicationContext; @ Test public void testListener () {NotifyEvent event = new NotifyEvent ("object", "abc@qq.com", "This is the content"); webApplicationContext.publishEvent (event);}}

By performing the unit test, you can see that the address and contents of the email have been printed.

2. CommandLineRunner interface of SpringBoot

When the container context is initialized, SpringBoot also calls all run methods that implement the CommandLineRunner interface. The following code can have the same effect as above:

@ Component public class CommandLineAppStartupRunner implements CommandLineRunner {private static final Logger LOG = LoggerFactory.getLogger (CommandLineAppStartupRunner.class); public static int counter; @ Override public void run (String...args) throws Exception {LOG.info ("Increment counter"); counter++;}}

There are two additional points to note about the use of this extension point:

The execution order of multiple Bean that implements CommandLineRunner can be adjusted according to the @ Order annotation on Bean.

Its run method can accept the parameters input from the console, which is more flexible than the extension of ApplicationListener.

/ / input parameters from the console example java-jar CommandLineAppStartupRunner.jar abc abcd3, ApplicationRunner interface of SpringBoot

This extension is similar to the extension of SpringBoot's CommandLineRunner interface, except that the accepted parameter is an ApplicationArguments class, which provides a better encapsulation of the parameters entered by the console, and the one starting with-- is regarded as a parameter with options, otherwise it is a normal parameter.

@ Component public class AppStartupRunner implements ApplicationRunner {private static final Logger LOG = LoggerFactory.getLogger (AppStartupRunner.class); public static int counter; @ Override public void run (ApplicationArguments args) throws Exception {LOG.info ("Application started with option names: {}", args.getOptionNames ()); LOG.info ("Increment counter"); counter++;}}

For example:

Java-jar CommandLineAppStartupRunner.jar abc abcd-autho=mark verboseBean initialization completes the extension point

The previous content summarizes the extension points initialized for the container. In some scenarios, such as listening to messages, we want to register the listener immediately after Bean initialization is completed, instead of waiting for the entire container to be refreshed. Spring also leaves enough extension points for this scenario:

1. @ PostConstruct annotation @ PostConstruct annotation is generally placed on the method of Bean. The method modified by @ PostConstruct will be called immediately after Bean initialization: @ Component public class PostConstructExampleBean {private static final Logger LOG = Logger.getLogger (PostConstructExampleBean.class); @ Autowired private Environment environment; @ PostConstruct public void init () {LOG.info (Arrays.asList (environment.getDefaultProfiles ();}} 2, InitializingBean interface

The usage of InitializingBean is basically the same as @ PostConstruct, except that the corresponding Bean needs to implement the afterPropertiesSet method

@ Component public class InitializingBeanExampleBean implements InitializingBean {private static final Logger LOG = Logger.getLogger (InitializingBeanExampleBean.class); @ Autowired private Environment environment; @ Override public void afterPropertiesSet () throws Exception {LOG.info (Arrays.asList (environment.getDefaultProfiles ());}} 3, @ Bean Annotation initialization method

You can specify the initialization method when injecting Bean through @ Bean:

Definition of Bean

Public class InitMethodExampleBean {private static final Logger LOG = Logger.getLogger (InitMethodExampleBean.class); @ Autowired private Environment environment; public void init () {LOG.info (Arrays.asList (environment.getDefaultProfiles ());}}

Bean injection

@ Bean (initMethod= "init") public InitMethodExampleBean initMethodExampleBean () {return new InitMethodExampleBean ();} 4. Inject via constructor

Spring also supports injection through the constructor, so we can write troublesome code in the constructor, and we can also achieve our goal.

@ Component public class LogicInConstructorExampleBean {private static final Logger LOG = Logger.getLogger (LogicInConstructorExampleBean.class); private final Environment environment; @ Autowired public LogicInConstructorExampleBean (Environment environment) {this.environment = environment; LOG.info (Arrays.asList (environment.getDefaultProfiles ();}} Bean initialization completes the extension point execution order?

You can use a simple test:

@ Component @ Scope (value = "prototype") public class AllStrategiesExampleBean implements InitializingBean {private static final Logger LOG = Logger.getLogger (AllStrategiesExampleBean.class); public AllStrategiesExampleBean () {LOG.info ("Constructor");} @ Override public void afterPropertiesSet () throws Exception {LOG.info ("InitializingBean");} @ PostConstruct public void postConstruct () {LOG.info ("PostConstruct") } public void init () {LOG.info ("init-method");}}

Instantiate the Bean and output:

[main] INFO o.b.startup.AllStrategiesExampleBean-Constructor [main] INFO o.b.startup.AllStrategiesExampleBean-PostConstruct [main] INFO o.b.startup.AllStrategiesExampleBean-InitializingBean [main] INFO o.b.startup.AllStrategiesExampleBean-init-method about how the seven startup extension points left to developers by SpringBoot are shared here. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report