Spring @EnableAutoConfiguration注解简介及使用示例
下文笔者讲述@EnableAutoConfiguration注解的功能及示例说明,如下所示
@EnableAutoConfiguration注解简介
EnableAutoConfiguration是SpringBoot的一个特性 可根据classpath中的jar依赖 自动注册bean, 一般用于类或接口上 它尝试根据您添加的jar依赖项自动配置Spring应用程序的IOC容器中 那么@EnableAutoConfiguration注解就是帮助SpringBoot程序完成这一自动装配功能 当然 @EnableAutoConfiguration注解 程序的原理,在框架SpringBoot的源码中
@EnableAutoConfiguration注解示例
1.编写自动装配类 package java265.beanConfig; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @Data //省略get set toString的编写 @ConfigurationProperties(prefix = "spring.user") public class User { private String name; } 2.配置信息 spring.factories(注意spring.factories的位置) # 自动装配 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ java265.beanConfig.User 3.bean属性配置 application.yml spring: user: name: java265 4.测试获取自动装配bean package java265; import java265.beanConfig.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ApplicationTest { @Autowired private User user; @Test public void testAutoCfg() { System.out.println(user); } } 5.打印输出 User(name=java265) 6.pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>java265</groupId> <artifactId>spring-boot-auto</artifactId> <version>1.0.0.RELEASE</version> <packaging>jar</packaging> <name>auto-boot</name> <description>EnableAutoConfiguration-demo</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.3.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。