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

An example Analysis of the underlying principle of Spring Boot

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

Share

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

Most people do not understand the knowledge points of this article "case Analysis of the underlying principles of Spring Boot", so the editor summarizes the following, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "case Analysis of Spring Boot underlying principles" article.

1. Underlying annotation @ Configuration

The @ Configuration annotation is mainly used to add components (Bean) to the container. Practice its usage below:

Basic project structure:

Two Bean components:

User.java

Package com.menergy.boot.bean; / * user * / public class User {private String name; private Integer age; public User () {} public User (String name, Integer age) {this.name = name; this.age = age; public String getName () {return name; public void setName (String name) {public Integer getAge () {return age Public void setAge (Integer age) {@ Override public String toString () {return "User {" + "name='" + name +'\'+ ", age=" + age +'}';}

Pet.java

Package com.menergy.boot.bean; / * * Pet * / public class Pet {private String name; public Pet () {} public Pet (String name) {this.name = name; public String getName () {return name Public void setName (String name) {@ Override public String toString () {return "Pet {" + "name='" + name +'\'+'}';}

In the past, the Spring configuration file added components to the container as follows:

Now that Spring Boot doesn't write the above xml configuration, you can use the @ Configuration annotation to add components to the container at the bottom of Spring Boot. As follows:

Annotated MyConfig.java

Package com.menergy.boot.config; import com.menergy.boot.bean.Pet;import com.menergy.boot.bean.User;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * 1. The @ Bean tag is used in the configuration class to register the component to the container on the method. The default is also * 2 of the single instance. The configuration class itself is also a component * 3. ProxyBeanMethods: proxy Bean method: * Full (proxyBeanMethods = true): no matter how many times the external registers the method on this component in the configuration class, it gets the single instance object in the previously registered container * Lite (proxyBeanMethods = false): proxy objects are not retained in the container, and when these components are called externally multiple times Each call produces a new object * used to resolve the component dependency scenario * / @ Configuration (proxyBeanMethods = true) / / tells SpringBoot that this is a configuration class = = previous configuration file public class MyConfig {/ * external no matter how many times the registration method is called for this component in the configuration class All you get is the single instance object * @ return * / @ Bean / / in the previously registered container to add the component to the container, using the method name as the primary key id, the return type is the component type, and the returned value is the instance public User user01 () {return new User ("dragon", 18) of the component in the container. @ Bean ("tomcatPet") public Pet pet01 () {return new Pet ("dragonPet");}

Test calls in the main class MainApplication.java:

Package com.menergy.boot; import com.menergy.boot.bean.Pet;import com.menergy.boot.bean.User;import com.menergy.boot.config.MyConfig;import org.springframework.boot.SpringApplication;import org.springframework.boot.SpringBootConfiguration;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.annotation.ComponentScan;import sun.awt.geom.AreaOp / * * main program class * this annotation is equivalent to telling SpringBoot that this is a Spring boot application * / @ SpringBootApplication@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan ("com.menergy.boot") public class MainApplication {public static void main (String [] args) {/ / SpringApplication.run (MainApplication.class, args); / / 1. Return IOC container ConfigurableApplicationContext run = SpringApplication.run (MainApplication.class, args); / / 2. Check the container String [] names = run.getBeanDefinitionNames (); for (String name: names) {System.out.println (name);} / / 3. Get components from the container Pet pet1 = run.getBean ("tomcatPet", Pet.class); Pet pet2 = run.getBean ("tomcatPet", Pet.class); System.out.println ("component:" + (pet1 = = pet2)); / / 4. Com.menergy.boot.config.MyConfig$$EnhancerBySpringCGLIB$$3779496a@67a056f1 MyConfig myConfig = run.getBean (MyConfig.class); System.out.println (myConfig) / / if @ Configuration (proxyBeanMethods = true) proxy object calls the method, Spring Boot always checks whether the component exists in the container. If so, it will not create a new one, keeping the single instance of the component. User user01 = myConfig.user01 (); User user02 = myConfig.user01 (); System.out.println (user01 = = user02);}}

Some of the output results:

In the above example, the focus is on the @ Configuration (proxyBeanMethods = true) annotation. This annotation tells SpringBoot that the annotated class is a configuration class, equivalent to the "bean configuration" in the previous configuration file xml. This annotation has the following features:

1. The @ Bean tag is used in the configuration class of this annotation to register the component with the container on the method, which is also single instance by default.

two。 The configuration class annotated by this is itself a component.

3. The attribute proxyBeanMethods of this annotation can control the mode used by configuring values of "true" and "false":

(1) Full pattern (proxyBeanMethods = true): when true, no matter how many times the external registration method is called on the component in the configuration class, it gets the single instance object in the previously registered container.

(2) Lite mode (proxyBeanMethods = false): when false, the proxy object is not retained in the container, and when these components are called multiple times from the outside, a new object is generated for each call.

The existence of these two modes is mainly used to solve component dependency scenarios.

Both 1 and 2 features are reflected in the above examples, and then focus on the third feature:

Practice proxyBeanMethods:

Based on the above example, first modify the User.java class to add the pet Pet dependency:

Package com.menergy.boot.bean; / * user * / public class User {private String name; private Integer age; private Pet pet; public User () {} public User (String name, Integer age) {this.name = name; this.age = age; public User (String name, Integer age, Pet pet) {this.pet = pet; public String getName () {return name Public void setName (String name) {public Integer getAge () {return age; public void setAge (Integer age) {public Pet getPet () {return pet Public void setPet (Pet pet) {@ Override public String toString () {return "User {" + "name='" + name +'\'+ ", age=" + age + ", pet=" + pet +'}';}

Add the user01 object to the pet object in the configuration class MyConfig.java, and use the Full schema (proxyBeanMethods = true):

Package com.menergy.boot.config; import com.menergy.boot.bean.Pet;import com.menergy.boot.bean.User;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * 1. The @ Bean tag is used in the configuration class to register the component to the container on the method. The default is also * 2 of the single instance. The configuration class itself is also a component * 3. ProxyBeanMethods: proxy Bean method: * Full mode (proxyBeanMethods = true): no matter how many times the external registers the method on this component in the configuration class, it gets the single instance object in the previously registered container * Lite pattern (proxyBeanMethods = false): proxy objects are not retained in the container, and when these components are called externally multiple times Each call produces a new object * used to resolve the component dependency scenario * / @ Configuration (proxyBeanMethods = true) / / tells SpringBoot that this is a configuration class = = previous configuration file public class MyConfig {/ * external no matter how many times the registration method is called for this component in the configuration class All you get is the single instance object * @ return * / @ Bean / / in the registered container to add the component to the container, using the method name as the primary key id, the return type is the component type, and the returned value is the instance public User user01 () {User dragonUser = new User ("dragon", 18) of the component in the container. / / User components depend on Pet components. When proxyBeanMethods is true, this dependency holds dragonUser.setPet (pet01 ()); return dragonUser;} @ Bean ("tomcatPet") public Pet pet01 () {return new Pet ("dragonPet");}

The main class MainApplication.java:

Package com.menergy.boot; import com.menergy.boot.bean.Pet;import com.menergy.boot.bean.User;import com.menergy.boot.config.MyConfig;import org.springframework.boot.SpringApplication;import org.springframework.boot.SpringBootConfiguration;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.annotation.ComponentScan;import sun.awt.geom.AreaOp / * * main program class * this annotation is equivalent to telling SpringBoot that this is a Spring boot application * / @ SpringBootApplication@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan ("com.menergy.boot") public class MainApplication {public static void main (String [] args) {/ / SpringApplication.run (MainApplication.class, args); / / 1. Return IOC container ConfigurableApplicationContext run = SpringApplication.run (MainApplication.class, args); / / 2. Check the container String [] names = run.getBeanDefinitionNames (); for (String name: names) {System.out.println (name);} / / 3. Get components from the container Pet pet1 = run.getBean ("tomcatPet", Pet.class); Pet pet2 = run.getBean ("tomcatPet", Pet.class); System.out.println ("component:" + (pet1 = = pet2)); / / 4. Com.menergy.boot.config.MyConfig$$EnhancerBySpringCGLIB$$3779496a@67a056f1 MyConfig myConfig = run.getBean (MyConfig.class); System.out.println (myConfig) / / if @ Configuration (proxyBeanMethods = true) proxy object calls the method, Spring Boot always checks whether the component exists in the container. If so, it will not create a new one, keeping the single instance of the component. User user01 = myConfig.user01 (); User user02 = myConfig.user01 (); System.out.println (user01 = = user02); / / Test @ Configuration (proxyBeanMethods = true/false) User user011 = run.getBean ("user01", User.class); Pet tomcatPet = run.getBean ("tomcatPet", Pet.class); System.out.println ("user's Pet:" + (user011.getPet () = tomcatPet));}}

Running result:

As you can see, when in Full mode (proxyBeanMethods = true), the output true indicates that it is the same component obtained from the container (the user's pet is the pet in the container).

Next, use the Lite mode (proxyBeanMethods = false): based on the above example, change the attribute proxyBeanMethods of the annotation in the configuration class MyConfig.java to the false value, as follows:

MyConfig.java:

Package com.menergy.boot.config; import com.menergy.boot.bean.Pet;import com.menergy.boot.bean.User;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * 1. The @ Bean tag is used in the configuration class to register the component to the container on the method. The default is also * 2 of the single instance. The configuration class itself is also a component * 3. ProxyBeanMethods: proxy Bean method: * Full mode (proxyBeanMethods = true): no matter how many times the external registers the method on this component in the configuration class, it gets the single instance object in the previously registered container * Lite pattern (proxyBeanMethods = false): proxy objects are not retained in the container, and when these components are called externally multiple times Each call produces a new object * used to resolve the component dependency scenario * / @ Configuration (proxyBeanMethods = false) / / tells SpringBoot that this is a configuration class = = previous configuration file public class MyConfig {/ * external no matter how many times the registration method is called for this component in the configuration class All you get is the single instance object * @ return * / @ Bean / / in the registered container to add the component to the container, using the method name as the primary key id, the return type is the component type, and the returned value is the instance public User user01 () {User dragonUser = new User ("dragon", 18) of the component in the container. / / User components depend on Pet components. When proxyBeanMethods is true, this dependency holds dragonUser.setPet (pet01 ()); return dragonUser;} @ Bean ("tomcatPet") public Pet pet01 () {return new Pet ("dragonPet");}

Running result:

As you can see, in Lite mode (proxyBeanMethods = false), false is output, indicating that it is not the same component that was obtained from the container (the user's pet is not a pet in the container, which is equivalent to new another object).

Summary: configuration classes include full mode (Full) and lightweight mode (Lite). When proxyBeanMethods is true, Spring Boot checks whether there is a corresponding component in the container every time. If proxyBeanMethods is false, it does not check whether there is a corresponding component in the container, but directly new one. This is also a very important feature added to Spring Boot.

Best practice: if you just add a component to the container, it won't be called anywhere else, but we can set it to false mode so that Spring Boot starts very quickly and loads very quickly. If it is obvious that it needs to be used elsewhere and depends on it, we adjust it to true to make sure that the dependent component is the component in the container.

Note: in the previous example, the @ Been annotation is used to specify components in the configuration class, but Spring Boot also uses other annotations commonly used in the past to specify components, including @ Component, @ Controller, @ Service, and @ Repository. These are similar to the @ Been principle and are also used to register components with the container.

In addition, the bottom layer uses the @ ComponentScan annotation to describe the package scanning of the container, and @ Import and @ Conditional to add components to the container. Many of the annotations are commonly used in the past, and then we focus on @ Import and @ Conditional annotations.

two。 Underlying annotation @ Import

First, you can see the definition of the annotation from the @ Import annotation class, as well as an array of Class type properties, indicating that the purpose of this annotation is to import a batch of components into the container:

Next, put it into practice:

First, add the @ Import annotation to the configuration class, and import two components into the container, one is a self-defined class, and the other is any class from a third-party Jar package:

The following tests are added to the main class:

Running result:

The results show that:

"com.menergy.boot.bean.User" is a component imported through @ Import. (the default component name is full class name)

"user01" was previously added with the @ Bean method

"org.apache.logging.log4j.util.StringBuilders@4482469c" is also a component imported through @ Import.

3. Underlying annotation @ Conditional

@ Conditional is a conditional assembly: components are injected into the container only when the conditions specified by @ Conditional are met.

Search for the @ Conditional class in the global Jar package: double-click the shift key, select Classes, and enter @ Conditional to search.

After opening the Conditional class, the "Ctrl + H" key calls up the inheritance tree of the class:

Note: if the shortcut key fails, please make sure the following shortcut key settings are set:

As you can see from the previous @ Conditional inheritance tree, @ Conditional has a lot of derived annotations, each of which represents a different function. From the name of the derived annotation, you can get a rough idea of its functional purpose. For example, the @ ConditionalOnBean annotation means to do something when a Bean exists in the container, and the @ ConditionalOnMissingBean annotation means to do something when a Bean does not exist in the container.

The above is about the content of this article "case Analysis of the underlying principles of Spring Boot". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

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