Spring Boot @configurationProperties.
在本教程中,我们将看到Spring Boot @configurationProperties注释。
Spring Boot @configurationProperties允许我们轻松地将具有Java对象的属性值映射。
让我们首先看到正常的映射。
假设我们有以下属性文件。
application.properties.
org.blogname=theitroad org.host=hostEasy
我们可以访问以下属性文件如下。
package org.igi.theitroad; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class BlogDetails { @Value("${org.blogName}") String blogName; @Value("${org.host}") String host; public String getBlogName() { return blogName; } public void setBlogName(String blogName) { this.blogName = blogName; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } }
因此,我们可以使用@Value从Application.properties从Application.properties获取属性值,但它可能会繁琐才能在各处使用@Value,Spring Boot提供@configurationProperties以将属性值映射到Java对象。
让我们通过示例来理解。
步骤1:使用名为"springboothelly申请"的Eclipse中的Maven创建动态Web项目。
maven依赖项:
第2步:更改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>org.igi.theitroad</groupId> <artifactId>SpringBootConfigurationPropertiesExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBootConfigurationPropertiesExample</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath <!-- lookup parent from repository --> </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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
第3步:创建名为"org.igi.theitroad"的包和名为serverdetail的类
package org.igi.theitroad; import java.util.Arrays; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix="com.server") public class ServerDetails { String url; String name; int[] port; Application application; public static class Application { String userName; String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int[] getPort() { return port; } public void setPort(int[] port) { this.port = port; } public Application getApplication() { return application; } public void setApplication(Application application) { this.application = application; } @Override public String toString() { return "Server Details{" + "name='" + name + '\'' + ", url='" + url + '\'' + ", port='" + Arrays.toString(port) + '\'' + ", username='" + application.getUserName()+ '\'' + ", password='" + application.getPassword()+ '\'' + '}'; } }
步骤4:更改应用程序.properties以添加以下属性。
org.blogName=theitroad org.host=hostEasy com.server.url= dummy.xyz.com com.server.name= amazonEc2 com.server.port[0]=8080 com.server.port[1]=8081 com.server.application.username = admin com.server.application.password = admin123
第5步:创建Spring Boot Main类。
package org.igi.theitroad; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class SpringBootExample { @Autowired ServerDetails serverDetails; public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(SpringBootExample.class, args); } @PostConstruct public void init() { System.out.println(serverDetails.toString()); } }
正如我们所看到的,我们使用@autowired将ServerDetail注入SpringBootexample。
步骤6:运行应用程序。
运行上面的示例时,我们将得到以下输出。
. ____ _ __ _ _ /\/___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )___ | '_ | '_| | '_ \/_` | \ \ \ \ \/___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |___, |//// =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.3.RELEASE) 2016-07-14 23:53:47.766 INFO 67832 — [ main] org.igi.theitroad.SpringBootExample : Starting SpringBootExample on apples-MacBook-Air.local with PID 67832 (/Users/apple/Downloads/SpringBootConfigurationPropertiesExample/target/classes started by apple in /Users/apple/Downloads/SpringBootConfigurationPropertiesExample) 2016-07-14 23:53:47.774 INFO 67832 — [ main] org.igi.theitroad.SpringBootExample : No active profile set, falling back to default profiles: default 2016-07-14 23:53:47.901 INFO 67832 — [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@429bd883: startup date [Sat May 14 23:53:47 IST 2016]; root of context hierarchy Server Details{name='amazonEc2′, url='dummy.xyz.com', port='[8080, 8081]', username='admin', password='admin123′} 2016-07-14 23:53:49.000 INFO 67832 — [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2016-07-14 23:53:49.024 INFO 67832 — [ main] org.igi.theitroad.SpringBootExample : Started SpringBootExample in 2.252 seconds (JVM running for 3.406) 2016-07-14 23:53:49.028 INFO 67832 — [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@429bd883: startup date [Sat May 14 23:53:47 IST 2016]; root of context hierarchy 2016-07-14 23:53:49.030 INFO 67832 — [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
这是图片,它将更好地了解@ConfigurationProperties。
宽松绑定
Spring boot的一个有趣特征是放松的绑定。
对于com.server.Application.Username,下面是有效的Spring Boot绑定。
- com.server.Application.User_name(使用_)
- com.server.Application.User-name(使用 - )
- com.server.application.user_name(用大写)
自定义属性文件
我们也可以使用自定义属性而不是应用程序。
使用@propertysource注释。
package org.igi.theitroad; import java.util.Arrays; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @PropertySource("classpath:custom.properties") @ConfigurationProperties(prefix="com.server") public class ServerDetails { .. }
验证
我们可以使用JSR-303验证API验证属性。
我们需要添加以下依赖项。
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.10.Final</version> <relativePath </dependency>
例如:假设我们希望将用户名限制为5到8个字符,我们可以使用@Length Annotaton如下所示。
@Length(max = 8, min = 5) String userName;
如果将用户名更改为亚当
com.server.application.username = adam
我们将获得以下验证错误。
Property:.com.server.application.username Value: adam Reason: length must be between 5 and 8