In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use Auto onfiguration of the four artifacts of SpringBoot". In daily operation, I believe many people have doubts about how to use Auto onfiguration of the four artifacts of SpringBoot. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to use Auto onfiguration of the four artifacts of SpringBoot." Next, please follow the editor to study!
Spring Boot is very simple and easy to use, it hides a lot of content and doesn't need you to care. But a good developer might want to know what's going on behind Spring Boot autoconfiguration?
Spring Boot is not a new technology, but Spring Boot's initiator helps us configure several bean managed by Spring. When our project relies on these jar and starts the Spring application, Spring's Container container has created and managed the objects under the jar package.
In short, Spring Boot autoconfiguration represents a way to automatically configure Spring applications based on dependencies that exist on the classpath. You can also eliminate some of the bean contained in the automatic configuration class by definition. These can make development faster and easier.
The essence of springboot auto configuration is to automatically configure various bean of spring. Then the application can use bean directly through injection methods such as @ Autowired. For example, automatically configure bean such as redisTemplate,jdbcTemplate.
1. Create a Spring Boot application by launching a class
Creating a Spring Boot application is as simple as creating a startup class that contains main.
Import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ApplicationContext; @ SpringBootApplicationpublic class App {public static void main (String [] args) {ApplicationContext ctx = SpringApplication.run (App.class, args);}}
The above class is called the Spring Boot application startup class, and it guides and starts a Spring application through a java main () method. It usually contains the following:
Create an instance of Spring ApplicationContext.
Take a command line argument and change it to a Spring property.
Load all Spring Bean as configured. Other actions can be done according to the project requirements.
2. @ SpringBootApplication comment
This comment is actually a shortcut with three annotations applied.
2.1 @ SpringBootConfiguration
@ SpringBootConfiguration is a new annotation that appears in Spring Boot2. Previously, we all used the @ Configuration annotation, which can be replaced with @ Configuration, both of which implement the same function.
It indicates that the class is a configuration class and should be scanned for further configuration and bean definition.
2.2 @ EnableAutoConfiguration
This note is used to enable the automatic configuration of Spring Application Context and to try to guess and configure the bean you may need. Automatic configuration classes are usually applied based on your classpath and the bean you define.
Automatic configuration tries to be as smart as possible and step back as you define more of your own configurations. You can always use two methods to manually exclude any configuration that you do not want to apply:
Use excludeName ()
Use the properties in the spring.autoconfigure.exclude properties file.
2.3 @ ComponentScan
This annotation provides support for parallelism with Spring XML context:component-scan elements.
Either basePackageClasses () or basePackages () can define specific packages for scanning. If no specific package is defined, it will be scanned from the package of the class that declares this annotation.
3. Custom automatic configuration
To create a custom autoconfiguration, we need to create a class annotated @ Configuration and register it.
Let's create a custom configuration for the MySQL data source:
@ Configurationpublic class MySQLAutoconfiguration {/ /.}
The next necessary step is to register the class as an autoconfiguration candidate by adding the name of the class under the attribute org.springframework.boot.autoconfigure.EnableAutoConfiguration in the standard file resource / META-INF / spring.factories:
Org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.peterwanghao.samples.springboot.autoconfiguration.MySQLAutoconfiguration
If we want our autoconfiguration class to take precedence over other autoconfiguration candidates, we can add the @ AutoConfigureOrder (Ordered.HIGHEST_PRECEDENCE) annotation.
Autoconfiguration is designed using classes annotated with @ Conditional and bean so that autoconfiguration or its specific parts can be replaced.
Note that autoconfiguration is valid only if an autoconfigured bean is not defined in the application. If you define bean, the default value is overridden.
3.1 Class-based conditional annotations
Class conditions allows us to specify classes that are specified with the @ ConditionalOnClass annotation, or use the @ ConditionalOnMissingClass annotation to specify classes that do not exist on the classpath.
Let's specify that MySQLConfiguration will only be loaded if the class DataSource exists, in which case we can assume that the application will use the database:
@ Configuration@ConditionalOnClass (DataSource.class) public class MySQLAutoconfiguration {/ /...} 3.2 conditional comments based on Bean
If we only want to include bean if the specified bean exists, we can use the @ ConditionalOnBean and @ ConditionalOnMissingBean annotations.
For example, let's add an entityManagerFactory bean to our configuration class and specify that if there is a bean named dataSource and a bean named entityManagerFactory has not been defined, we create this bean:
@ Bean @ ConditionalOnBean (name = "dataSource") @ ConditionalOnMissingBean public LocalContainerEntityManagerFactoryBean entityManagerFactory () {final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean (); em.setDataSource (dataSource ()); em.setPackagesToScan ("com.peterwanghao.samples.springboot.autoconfiguration.example"); em.setJpaVendorAdapter (new HibernateJpaVendorAdapter ()); if (additionalProperties ()! = null) {em.setJpaProperties (additionalProperties ());} return em;}
Let's configure a transactionManager bean that will be loaded only if a bean of type JpaTransactionManager has not been defined:
@ Bean @ ConditionalOnMissingBean (type = "JpaTransactionManager") JpaTransactionManager transactionManager (final EntityManagerFactory entityManagerFactory) {final JpaTransactionManager transactionManager = new JpaTransactionManager (); transactionManager.setEntityManagerFactory (entityManagerFactory); return transactionManager;} 3.3 conditional comments based on attributes
The @ ConditionalOnProperty annotation is used to specify whether the configuration will be loaded based on the existence and value of the Spring environment property.
First, let's add an attribute source file to the configuration to determine where to read the attributes:
@ PropertySource ("classpath:mysql.properties") public class MySQLAutoconfiguration {/ /.}
We can configure the main DataSource bean, which will be used to create a connection to the database and will be loaded only if a property named usemysql exists.
We can use the attribute havingValue to specify some values of the usemysql attribute that must match.
If the usemysql property is set to local, let's define dataSource bean with the default value, which connects to the local database named myDb:
Bean @ ConditionalOnProperty (name = "usemysql", havingValue = "local") @ ConditionalOnMissingBean public DataSource dataSource () {final DriverManagerDataSource dataSource = new DriverManagerDataSource (); dataSource.setDriverClassName ("com.mysql.cj.jdbc.Driver"); dataSource.setUrl ("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true&&serverTimezone=GMT%2B8"); dataSource.setUsername ("root"); dataSource.setPassword ("123456"); return dataSource;}
If the usemysql property is set to custom, the data source bean is configured with the database URL, user, and password of the custom attribute value:
Bean (name = "dataSource") @ ConditionalOnProperty (name = "usemysql", havingValue = "custom") @ ConditionalOnMissingBean public DataSource dataSource2 () {final DriverManagerDataSource dataSource = new DriverManagerDataSource (); dataSource.setDriverClassName ("com.mysql.cj.jdbc.Driver"); dataSource.setUrl (env.getProperty ("mysql.url")); dataSource.setUsername (env.getProperty ("mysql.user")! = null? Env.getProperty ("mysql.user"): "); dataSource.setPassword (env.getProperty (" mysql.pass ")! = null? Env.getProperty ("mysql.pass"): ""); return dataSource;}
The mysql.properties file will contain the usemysql attribute:
Usemysql=local
If an application that uses MySQLAutoconfiguration wants to override the default properties, all it needs to do is add different values for the mysql.url,mysql.user and mysql.pass attributes in the mysql.properties file and add the line usemysql = custom.
3.4 Resource-based conditional annotations
Adding the @ ConditionalOnResource annotation means that the configuration is loaded only if the specified resource exists.
Let's define a method called additionalProperties (), which returns a Properties object that contains the Hibernate-specific properties used by entityManagerFactory bean, only if the resource file mysql.properties exists:
ConditionalOnResource (resources = "classpath:mysql.properties") @ Conditional (HibernateCondition.class) final Properties additionalProperties () {final Properties hibernateProperties = new Properties (); hibernateProperties.setProperty ("hibernate.hbm2ddl.auto", env.getProperty ("mysql-hibernate.hbm2ddl.auto")); hibernateProperties.setProperty ("hibernate.dialect", env.getProperty ("mysql-hibernate.dialect")); hibernateProperties.setProperty ("hibernate.show_sql", env.getProperty ("mysql-hibernate.show_sql")! = null? Env.getProperty ("mysql-hibernate.show_sql"): "false"); return hibernateProperties;}
We can add Hibernate-specific attributes to the mysql.properties file:
Mysql-hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialectmysql-hibernate.show_sql=truemysql-hibernate.hbm2ddl.auto=create-drop3.5 Custom condition
If we don't want to use any of the available conditions in SpringBoot, we can also define custom conditions by extending the SpringBootCondition class and overriding the getMatchOutcome () method.
Let's create a condition called HibernateCondition for the additionalProperties () method, which verifies that the HibernateEntityManager class exists on the classpath:
Static class HibernateCondition extends SpringBootCondition {private static final String [] CLASS_NAMES = {"org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager"}; @ Override public ConditionOutcome getMatchOutcome (ConditionContext context, AnnotatedTypeMetadata metadata) {ConditionMessage.Builder message = ConditionMessage.forCondition ("Hibernate") Return Arrays.stream (CLASS_NAMES) .filter (className-> ClassUtils.isPresent (className, context.getClassLoader () .map (className-> ConditionOutcome.match (message.found ("class") .items (Style.NORMAL, className)) .findAny (). OrElseGet ()-> ConditionOutcome.noMatch (message.didNotFind ("class", "classes") .items (Style.NORMAL, Arrays.asList (CLASS_NAMES);}}
Then we can add the condition to the additionalProperties () method:
@ Conditional (HibernateCondition.class) Properties additionalProperties () {/ /...} 3.6 Application conditions
We can also specify that the configuration can only be loaded inside / outside the Web context by adding @ ConditionalOnWebApplication or @ ConditionalOnNotWebApplication annotations.
4. Test automatic configuration
Let's create a very simple example to test our automatic configuration. We will use Spring Data to create an entity class named MyUser and an MyUserRepository interface:
@ Entitypublic class MyUser {@ Id private String email; public MyUser () {} public MyUser (String email) {super (); this.email = email;} public String getEmail () {return email;} public void setEmail (String email) {this.email = email;}} public interface MyUserRepository extends JpaRepository {}
To enable automatic configuration, we can use @ SpringBootApplication or @ EnableAutoConfiguration annotations:
@ SpringBootApplicationpublic class AutoconfigurationApplication {public static void main (String [] args) {SpringApplication.run (AutoconfigurationApplication.class, args);}}
Next, let's write a JUnit test that holds the MyUser entity:
RunWith (SpringJUnit4ClassRunner.class) @ SpringBootTest (classes = AutoconfigurationApplication.class) @ EnableJpaRepositories (basePackages = {"com.peterwanghao.samples.springboot.autoconfiguration.example"}) public class AutoconfigurationLiveTest {@ Autowired private MyUserRepository userRepository; @ Test public void whenSaveUser_thenOk () {MyUser user = new MyUser ("user@email.com"); userRepository.save (user);}}
Since we have not yet defined the DataSource configuration, the application will use the automatic configuration we created to connect to the MySQL database named myDb.
The connection string contains the createDatabaseIfNotExist = true attribute, so the database does not need to exist. However, you need to create a user mysqluser or a user mysqluser specified by the mysql.user attribute.
We can check the application log to see if we are using MySQL data sources:
10 HHH000412 31 HHH000412 47.092 [main] INFO org.hibernate.Version-HHH000412: Hibernate Core {5.3.7.Final}
10 HHH000206 31 HHH000206 47.094 [main] INFO org.hibernate.cfg.Environment-HHH000206: hibernate.properties not found
10 Hibernate Commons Annotations 31 HCANN000001 47.227 [main] INFO o.h.annotations.common.Version-HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
10 Using dialect 31 HHH000400 48.039 [main] HHH000400-Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
Hibernate: drop table if exists MyUser
Hibernate: create table MyUser (email varchar (255) not null, primary key (email)) engine=InnoDB
INFO o.h.t.s.internal.SchemaCreatorImpl-HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@3a0b6a'
10 Initialized JPA EntityManagerFactory for persistence unit 31 Initialized JPA EntityManagerFactory for persistence unit 48. 666 [main] Initialized JPA EntityManagerFactory for persistence unit 'default'
10 Initializing ExecutorService 31 Initializing ExecutorService 49 496 [main] INFO o.s.s.c.ThreadPoolTaskExecutor-Initializing ExecutorService 'applicationTaskExecutor'
10 main 31 spring.jpa.open-in-view is enabled by default 49.569 [main]. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
10 main 31VR 49.701 [main] WARN o.s.b.a.t.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration-Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
10 seconds 31 Started AutoconfigurationLiveTest in 50.091 [main] INFO c.p.s.s.a.AutoconfigurationLiveTest-Started AutoconfigurationLiveTest in 4.803 seconds (JVM running for 5.519)
Hibernate: select myuser0_.email as email1_0_0_ from MyUser myuser0_ where myuser0_.email=?
Hibernate: insert into MyUser (email) values (?)
10 Shutting down ExecutorService 31 Shutting down ExecutorService 50.279 [Thread-2] INFO o.s.s.c.ThreadPoolTaskExecutor-Shutting down ExecutorService 'applicationTaskExecutor'
10Rose 31Rose 50.281 [Thread-2] INFO o.s.o.j.LocalContainerEntityManagerFactoryBean-Closing JPA EntityManagerFactory for persistence unit 'default'
10 Thread-2 31VR 50.282 [Thread-2] INFO o.h.t.s.i.SchemaDropperImpl$DelayedDropActionImpl-HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
Hibernate: drop table if exists MyUser
5. Disable automatic configuration classes
If we want to exclude automatic configuration from the load, we can add the @ EnableAutoConfiguration annotation with the exclude or excludeName attribute to the configuration class:
@ Configuration@EnableAutoConfiguration (exclude= {MySQLAutoconfiguration.class}) public class AutoconfigurationApplication {/ /.}
Another way to disable a specific autoconfiguration is to set the spring.autoconfigure.exclude property:
Spring.autoconfigure.exclude=com.peterwanghao.samples.springboot.autoconfiguration.MySQLAutoconfiguration at this point, on the "four artifacts of SpringBoot how to use Auto onfiguration" on the end of the study, I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.