【Spring boot】【03】【项目的配置文件不同的使用方式】

1.我们首先创建一个“spring-boot-config”的项目

【Spring boot】【03】【项目的配置文件不同的使用方式】

2.我们在“application.properties”添加配置项目

spring.boot.name="乔帮主"
spring.boot.sex="男"
spring.boot.age="27"

3.我们创建“config”类

【Spring boot】【03】【项目的配置文件不同的使用方式】
UserOneConfig.java的配置类如下:

package com.qjc.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author qjc
 * @date 2019年1月24日下午2:17:53
 * @version 1.0.0
 */
@Component
@ConfigurationProperties(prefix="spring.boot")
public class UserOneConfig {
	/**
	 * 姓名
	 */
	private String name;
	/**
	 * 性别
	 */
	private String sex;
	/***
	 * 年龄
	 */
	private String age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
	
	
}

UserTwoConfig.java的配置类如下:

package com.qjc.config;

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

/**
 * @author qjc
 * @date 2019年1月24日下午2:31:33
 * @version 1.0.0
 */
@Component
public class UserTwoConfig {
	/**
	 * 姓名
	 */
	@Value("${spring.boot.name}")
	private String name;
	/**
	 * 性别
	 */
	@Value("${spring.boot.sex}")
	private String sex;
	/***
	 * 年龄
	 */
	@Value("${spring.boot.age}")
	private String age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
}

4.我们可以直接在测试“Test”类进行测试

package com.qjc;

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;

import com.qjc.config.UserOneConfig;
import com.qjc.config.UserTwoConfig;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootConfigApplicationTests {

	@Autowired
	UserOneConfig userOneConfig;

	@Autowired
	UserTwoConfig userTwoConfig;

	@Test
	public void contextLoads() {
		System.out.println(
				"name:" + userOneConfig.getName() + "sex:" + userOneConfig.getSex() + "sex:" + userOneConfig.getAge());
		System.out.println("name:" + userTwoConfig.getName() + "sex:" + userTwoConfig.getSex() + "sex:"
				+ userTwoConfig.getAge());
	}

}

会发现都能获取配置文件的内容,打印结果:

14:54:33.146 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.qjc.SpringBootConfigApplicationTests]
14:54:33.152 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
14:54:33.160 [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)]
14:54:33.179 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.qjc.SpringBootConfigApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
14:54:33.193 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.qjc.SpringBootConfigApplicationTests], using SpringBootContextLoader
14:54:33.200 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.qjc.SpringBootConfigApplicationTests]: class path resource [com/qjc/SpringBootConfigApplicationTests-context.xml] does not exist
14:54:33.200 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.qjc.SpringBootConfigApplicationTests]: class path resource [com/qjc/SpringBootConfigApplicationTestsContext.groovy] does not exist
14:54:33.200 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.qjc.SpringBootConfigApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
14:54:33.201 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.qjc.SpringBootConfigApplicationTests]: SpringBootConfigApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
14:54:33.259 [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.qjc.SpringBootConfigApplicationTests]
14:54:33.349 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [D:\J2EEBoot\eclipse-boot\spring-boot-config\target\classes\com\qjc\SpringBootConfigApplication.class]
14:54:33.350 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.qjc.SpringBootConfigApplication for test class com.qjc.SpringBootConfigApplicationTests
14:54:33.441 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.qjc.SpringBootConfigApplicationTests]: using defaults.
14:54:33.441 [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]
14:54:33.451 [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]
14:54:33.451 [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]
14:54:33.451 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [or[email protected]7adda9cc, org.springframework.test[email protected]5cee5251, org.spri[email protected]433d61fb, org.springframework.boot.test.a[email protected]5c909414, org.springfra[email protected]4b14c583, org.springf[email protected]65466a6a, org.springframework[email protected]4ddced80, org.springframework.boot.test.autoconfi[email protected]1534f01b, org.springframework.boot.test.autoconfi[email protected]78e117e3, org.springframework.boo[email protected]2ea227af]
14:54:33.453 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.453 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.454 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.455 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.464 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.464 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.465 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.465 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.465 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.465 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.470 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [[email protected] testClass = SpringBootConfigApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [[email protected] testClass = SpringBootConfigApplicationTests, locations = '{}', classes = '{class com.qjc.SpringBootConfigApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springfr[email protected]4fe3c938, org.springframework.boot.test.json.DuplicateJsonObje[email protected]71423665, org.[email protected]0, org.springf[email protected]369f73a2, org.springframework.boot[email protected]0, org.springframework.boot.test.autocon[email protected]578486a3], 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].
14:54:33.471 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.471 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.qjc.SpringBootConfigApplicationTests]
14:54:33.492 [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.2.RELEASE)

2019-01-24 14:54:33.768  INFO 5768 --- [           main] c.qjc.SpringBootConfigApplicationTests   : Starting SpringBootConfigApplicationTests on DESKTOP-580CUKI with PID 5768 (started by joe in D:\J2EEBoot\eclipse-boot\spring-boot-config)
2019-01-24 14:54:33.770  INFO 5768 --- [           main] c.qjc.SpringBootConfigApplicationTests   : No active profile set, falling back to default profiles: default
2019-01-24 14:54:35.211  INFO 5768 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-01-24 14:54:35.466  INFO 5768 --- [           main] c.qjc.SpringBootConfigApplicationTests   : Started SpringBootConfigApplicationTests in 1.959 seconds (JVM running for 2.717)
name:"qjc"sex:"man"sex:"27"
name:"qjc"sex:"man"sex:"27"
2019-01-24 14:54:35.610  INFO 5768 --- [       Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

5.项目源码地址
https://github.com/joecheng521/springboot/tree/master/spring-boot-config