springboot自定义属性

1.新建一个maven工程springboot,添加相关依赖,pom文件类容如下:

<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>com.szcatic</groupId>
  <artifactId>springboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot</name>
  <url>http://maven.apache.org</url>
  
  	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
        <!-- junit5运行所需jar包 -->
		<dependency>
		    <groupId>org.junit.jupiter</groupId>
		    <artifactId>junit-jupiter-engine</artifactId>
		    <scope>test</scope>
		</dependency>
		<dependency>
		    <groupId>org.junit.platform</groupId>
		    <artifactId>junit-platform-runner</artifactId>
		    <scope>test</scope>
		</dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
	                <source>1.8</source>
	                <target>1.8</target>
	            </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2.在/src/main/resources/资源文件夹下新建文件config.properties,类容如下:

com.szcatic.title=标题
com.szcatic.name=名字
com.szcatic.description=${com.szcatic.title}${com.szcatic.name}描述

3.创建配置文件类实体CustomizeProperties.java

package com.szcatic.properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = "classpath:config.properties", encoding = "UTF-8")
public class CustomizeProperties {
	
	@Value("${com.szcatic.name}")
	private String name;
	
	@Value("${com.szcatic.title}")
	private String title;
	
	@Value("${com.szcatic.description}")
	private String description;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}
	
	
}

4.创建应用程序入口Application.java

package com.szcatic;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;

@ComponentScan(basePackages = {"com"})
@SpringBootApplication
public class Application {
	
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
	@RequestMapping("/hello")
    public String getHello() {
        return "Hello World";
    }
}

 5.创建测试类

package com.szcatic.test;

import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import com.szcatic.Application;
import com.szcatic.properties.CustomizeProperties;

@Configuration
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Application.class)
public class CustomizePropertiesTest {
	
	@Autowired
	private CustomizeProperties properties;
	
	@Test
	void testGet() {
		Assert.assertEquals(properties.getName(), "名字");
		Assert.assertEquals(properties.getTitle(), "标题");
		Assert.assertEquals(properties.getDescription(), "标题名字描述");
		System.out.println("测试成功");
	}
	
}

6.运行测试方法testGet,获得测试结果

10:01:04.054 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
10:01:04.078 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
10:01:04.098 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.szcatic.test.CustomizePropertiesTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
10:01:04.111 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.szcatic.test.CustomizePropertiesTest], using SpringBootContextLoader
10:01:04.115 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.szcatic.test.CustomizePropertiesTest]: class path resource [com/szcatic/test/CustomizePropertiesTest-context.xml] does not exist
10:01:04.116 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.szcatic.test.CustomizePropertiesTest]: class path resource [com/szcatic/test/CustomizePropertiesTestContext.groovy] does not exist
10:01:04.116 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.szcatic.test.CustomizePropertiesTest]: no resource found for suffixes {-context.xml, Context.groovy}.
10:01:04.172 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.szcatic.test.CustomizePropertiesTest]
10:01:04.300 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.szcatic.test.CustomizePropertiesTest]: using defaults.
10:01:04.300 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
10:01:04.309 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
10:01:04.310 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
10:01:04.310 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@58a9760d, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@71e9ddb4, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@394df057, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@4961f6af, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5aebe890, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@65d09a04, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@33c911a1, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@75db5df9, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@707194ba, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@1190200a]
10:01:04.314 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@1757cd72 testClass = CustomizePropertiesTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@445b295b testClass = CustomizePropertiesTest, locations = '{}', classes = '{class com.szcatic.Application, class com.szcatic.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3a079870, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5c1a8622, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@1460a8c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@7fc2413d], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
10:01:04.343 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2018-11-19 10:01:04.703  INFO 8268 --- [           main] c.szcatic.test.CustomizePropertiesTest   : Starting CustomizePropertiesTest on zsx with PID 8268 (started by admin in F:\workspace4.7\springboot)
2018-11-19 10:01:04.705  INFO 8268 --- [           main] c.szcatic.test.CustomizePropertiesTest   : No active profile set, falling back to default profiles: default
2018-11-19 10:01:08.333  INFO 8268 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2018-11-19 10:01:08.704  INFO 8268 --- [           main] c.szcatic.test.CustomizePropertiesTest   : Started CustomizePropertiesTest in 4.349 seconds (JVM running for 5.332)
测试成功
2018-11-19 10:01:09.278  INFO 8268 --- [       Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

 

7.目录结构

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值