In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to master Spring". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to master Spring".
Spring is a container that controls reverse dependency management. As Java Web developers, there is basically no one who is not familiar with the Spring technology stack, although in the field of dependency injection, there is no lack of other excellent frameworks in the field of Java Web, such as google's open source dependency management framework guice, such as the Jersey web framework. But Spring has been the most widely used and widely used Java framework in the field of Java Web.
This article will focus on how to implement the logic we want to implement when the Spring container starts. We often encounter some initialization operations that have to be completed when Spring starts, such as creating scheduled tasks, creating connection pools, and so on.
If there is no Spring container, do not rely on the implementation of Spring, return to the Java class implementation itself, we can implement the corresponding logic in the static code block and in the class constructor. The initialization order of the Java class is static variable > static code block > global variable > initialization code block > constructor.
For example, the initialization of Log4j is implemented in the static code block of LogManager:
Static {Hierarchy h = new Hierarchy (new RootLogger ((Level) Level.DEBUG)); repositorySelector = new DefaultRepositorySelector (h); String override = OptionConverter.getSystemProperty (DEFAULT_INIT_OVERRIDE_KEY,null); if (override = = null | | "false" .equalsIgnoreCase (override)) {String configurationOptionStr = OptionConverter.getSystemProperty (DEFAULT_CONFIGURATION_KEY, null); String configuratorClassName = OptionConverter.getSystemProperty (CONFIGURATOR_CLASS_KEY, null); URL url = null If (configurationOptionStr = = null) {url = Loader.getResource (DEFAULT_XML_CONFIGURATION_FILE); if (url = = null) {url = Loader.getResource (DEFAULT_CONFIGURATION_FILE);}} else {try {url = new URL (configurationOptionStr) } catch (MalformedURLException ex) {url = Loader.getResource (configurationOptionStr);}} if (url! = null) {LogLog.debug ("Using URL [" + url+ "] for automatic log4j configuration."); try {OptionConverter.selectAndConfigure (url, configuratorClassName,LogManager.getLoggerRepository ()) } catch (NoClassDefFoundError e) {LogLog.warn ("Error during default initialization", e);}} else {LogLog.debug ("Could not find resource: [" + configurationOptionStr+ "].");}} else {LogLog.debug ("Default initialization of overridden by" + DEFAULT_INIT_OVERRIDE_KEY + "property.");}}
For example, implement the corresponding logic in the constructor:
@ Component public class CustomBean {@ Autowired private Environment env; public CustomBean () {env.getActiveProfiles ();}}
Here is a test to see if the above code works properly. -- No, the env in the constructor will have a NullPointException exception. This is because in Spring, the Bean will be initialized first, that is, the constructor of the class will be called first, and then the Bean of the member variable dependency (member variables modified by @ Autowired and @ Resource annotations) will be injected. Note that the injection of the configuration of annotations such as @ Value is also after the constructor.
PostConstruct
In Spring, we can use @ PostConstruct to implement the corresponding initialization logic after Bean initialization. The method modified by @ PostConstruct will be executed after Bean initialization, and then the dependency of Bean has been injected, so you can call the injected dependency Bean in the method.
Component public class CustomBean {@ Autowired private Environment env; @ PostConstruce public void init () {env.getActiveProfiles ();}}
Corresponding to @ PostConstruct, if you want to complete some cleaning work when Bean logs out, such as closing the thread pool, you can use the @ PreDestroy annotation:
Component public class CustomBean {@ Autowired private ExecutorService executor = Executors.newFixedThreadPool (1) @ PreDestroy public void destroy () {env.getActiveProfiles ();}}
InitializingBean
Implementing the InitializingBean interface of Spring can also implement the above function of executing the corresponding logic after the Bean initialization is completed, implement the InitializingBean interface, and implement the logic in the afterPropertiesSet method:
@ Component public class CustomBean implements InitializingBean {private static final Logger LOG = Logger.getLogger (InitializingBeanExampleBean.class); @ Autowired private Environment environment; @ Override public void afterPropertiesSet () throws Exception {LOG.info (environment.getDefaultProfiles ());}}
ApplicationListener
We can implement the initialization logic we want when the Spring container is initialized. At this point, we can use the initialization event of Spring. Spring has a complete event mechanism. When Spring starts, the Spring container itself presets a lot of events. In the whole process of Spring initialization, the corresponding events are triggered in the corresponding nodes. We can implement our initialization logic by listening for these events. The event implementation of Spring is as follows:
ApplicationEvent, the event object, is published by ApplicationContext, and different implementation classes represent different event types.
ApplicationListener, listening object. Any Bean that implements this API will receive the corresponding event notification. After implementing the ApplicationListener interface, you need to implement the method onApplicationEvent (), which is executed after the container has initialized all the Bean.
Several events related to the Spring Context lifecycle are as follows:
ApplicationStartingEvent: this event is sent when the Spring Boot application starts running and before any processing (except for listeners and initializers registration).
ContextRefreshedEvent: this event is published when the ApplicationContext is initialized or refreshed. This can also happen using the refresh () method in the ConfigurableApplicationContext interface.
ContextStartedEvent: this event is triggered when ApplicationContext is started using the start () method in the ConfigurableApplicationContext interface. You can query your database, or you can restart any stopped application after receiving this event.
ApplicationReadyEvent: this event is sent after any application/ command-line runners call.
ContextClosedEvent: this event is triggered when ApplicationContext is turned off using the close () method in the ConfigurableApplicationContext interface. A closed context reaches the end of the life cycle; it cannot be refreshed or restarted.
ContextStoppedEvent: the last event completed by Spring.
Therefore, if we want to implement some logic when Spring starts, we can find the events that meet our needs during Spring startup, and complete our logic by listening for the corresponding events:
@ Component @ Slf4j public class StartupApplicationListenerExample implements ApplicationListener {@ Override public void onApplicationEvent (ContextRefreshedEvent event) {log.info ("Subject ContextRefreshedEvent");}}
In addition to listening for corresponding events by implementing the ApplicationListener interface, Spring's event mechanism also implements listening for corresponding events through @ EventListener annotations:
@ Component @ Slf4j public class StartupApplicationListenerExample {@ EventListener public void onApplicationEvent (ContextRefreshedEvent event) {log.info ("Subject ContextRefreshedEvent");}}
Spring Event is a complete in-process event publish and subscribe mechanism. In addition to listening to Spring built-in events, we can also use Spring Event to implement custom event publish and subscribe functions.
Constructor injection
When we learn about the injection mechanism of Spring, we all know that Spring can be injected through constructors, Setter, and reflection member variables. Above, we inject dependency Bean on member variables through the @ Autoware annotation, but the injected Bean cannot be used in the constructor function of Bean (because Bean has not been injected yet). In fact, we also use the constructor injection method of Spring, which is also the injection mechanism recommended by Spring (when we use IDEA, if we do not turn off the corresponding code Warning mechanism, we will find that @ Autoware on the member variable is yellow. That is, code that idea does not recommend). Spring recommends constructor injection:
Component @ Slf4j public class ConstructorBean {private final Environment environment; @ Autowired public LogicInConstructorExampleBean (Environment environment) {this.environment = environment; log.info (Arrays.asList (environment.getDefaultProfiles ();}}
CommandLineRunner
If our project uses Spring Boot, we can use the CommandLineRunner interface provided by Spring Boot to implement the initialization logic. Spring Boot will call the run method that implements the CommandLineRunner interface after initialization is complete:
@ Component @ Slf4j public class CommandLineAppStartupRunner implements CommandLineRunner {@ Override public void run (String...args) throws Exception {log.info ("Increment counter");}}
Also, multiple CommandLineRunner implementations can control the order of their execution through @ Order.
SmartLifecycle
There is also a more advanced way to implement our logic. This is a must for Spring advanced development skills. SmartLifecycle can not only execute a logic after initialization, but also execute a logic before shutting down, and it can also control the execution order of multiple SmartLifecycle. As the class name indicates, this is an intelligent lifecycle management interface.
Start (): after the bean is initialized, the method is executed.
Stop (): after the container is closed, the spring container finds that the current object implements SmartLifecycle and calls stop (Runnable), and if only Lifecycle is implemented, stop () is called.
IsRunning: current state, which is used to determine whether your broken component is running.
GetPhase: controls the callback order of multiple SmartLifecycle, the smaller the return value, the more forward the start () method is executed, and the later the stop () method is executed.
IsAutoStartup (): look at the return value of this method before the start method is executed. If it returns false, the start method will not be executed.
Stop (Runnable): after the container is closed, the spring container finds that the current object implements SmartLifecycle and calls stop (Runnable), and if only Lifecycle is implemented, stop () is called.
@ Component public class SmartLifecycleExample implements SmartLifecycle {private boolean isRunning = false; @ Override public void start () {System.out.println ("start"); isRunning = true;} @ Override public int getPhase () {/ / default is 0 return 0;} @ Override public boolean isAutoStartup () {/ / defaults to false return true } @ Override public boolean isRunning () {/ / return false return isRunning;} @ Override public void stop (Runnable callback) {System.out.println ("stop (Runnable)"); callback.run (); isRunning = false;} @ Override public void stop () {System.out.println ("stop") IsRunning = false;}} Thank you for your reading. The above is the content of "how to master Spring". After the study of this article, I believe you have a deeper understanding of how to master Spring, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.