1. 程式人生 > >SpringBoot 入門之一:Configuration 和 Properties

SpringBoot 入門之一:Configuration 和 Properties

 

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

	<name>demoPro</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.0.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-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<!-- MYSQL -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- Spring Boot JDBC -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

 

Applicatoin.java

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ImportResource;


@ImportResource(locations={"classpath:beans.xml"})		// 此處是為了能過通過IOC方式獲取某個bean
@SpringBootApplication
//@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class DemoProApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoProApplication.class, args);
	}
}

 

application.properties, 注意此處通過啟用方式類引用其他的properties檔案,檔名如 application-testData.properties

spring.profiles.active=testData


spring.datasource.url=jdbc:mysql://localhost:3306/testDB
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

 application-testData.properties

server.port=8888

person.name=Shawn
person.age=23
person.birth=2018-01-01
person.maps.k1=v1
person.maps.k2=value2
person.lists=one,two,three
person.dog.name=Godname
person.dog.age=3


Person類

package com.test.JavaBean;

import java.util.List;
import java.util.Map;

import org.hibernate.validator.constraints.Email;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

/*
 *
 * @ConfigurationProperties 	如果,我們有javebean需要和peoperty中的屬性來對映獲值,則用@ConfigurationProperties,預設從全域性檔案中獲取
 * @Value						如果我們只是在某個業務邏輯中從peoperty檔案中獲取某個或幾個簡單型別的值,用@Value方式獲取
 */


@PropertySource(value = {"classpath:application-testData.properties"})	// 可以指定某個或某些配置檔案,效果同@ConfigurationProperties
@Component
@ConfigurationProperties(prefix="person")		//	字首跟properties檔案裡的父節點匹配,對映properties中對應屬性的值到當前javabean,此Bean需要get set方法
@Validated										// 此註解可以做JSR303資料驗證,只適用於@ConfigurationProperties 方式注入,@value不適用
public class Person {

	private String name;
	private Integer age;
	private  String birth;
	private Map<String, Object> maps;			// 如果獲取map型別的值,只適用於@ConfigurationProperties 方式注入獲取,@value不適用
	private List<Object> lists;
	private Dog dog;
	
	
	@Email
	@Value("[email protected]")							// 此處會驗證email的值,如果格式錯誤 會報錯
	private String email;
	
	
	@Value("${person.name}")
	private String tempName;					// 此處 用 Value註解方式獲取值
	
	
	@Value("${person.lists}")
	private List tempLists;

	@Override
	public String toString() {
		String personStrt =  "Person [name=" + name + ", age=" + age + ", birth=" + birth + ", maps=" + maps + ", lists=" + lists
				+ ", dog=" + dog + "]";
		
		
		System.out.println(tempName);
		System.out.println(email);	
		System.out.println(tempLists);	
		
		return personStrt;
	}

	public String getName() {
		return name;
	}

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

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getBirth() {
		return birth;
	}

	public void setBirth(String birth) {
		this.birth = birth;
	}

	public Map<String, Object> getMaps() {
		return maps;
	}

	public void setMaps(Map<String, Object> maps) {
		this.maps = maps;
	}

	public List<Object> getLists() {
		return lists;
	}

	public void setLists(List<Object> lists) {
		this.lists = lists;
	}

	public Dog getDog() {
		return dog;
	}

	public void setDog(Dog dog) {
		this.dog = dog;
	}

}

 SpringTest 測試類

package com.test;

import java.util.List;
import java.util.Map;

import org.hibernate.validator.constraints.Email;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.validation.annotation.Validated;

import com.test.JavaBean.Dog;
import com.test.JavaBean.Person;

@Validated	
@SpringBootTest
@RunWith(SpringRunner.class)
public class DemoProApplicationTests {

	@Autowired
	Person person1;
	
	@Test
	public void contextLoads() {				// 通過上下文person物件會在它自己類中從priperties檔案注入值
		System.out.println(person1);
	}
	
	@Email
	@Value("[email protected]")							// 此處會驗證email的值,如果格式錯誤 會報錯
	private String email;
	
	
	@Value("${person.lists}")						// 此處 用 Value註解方式獲取值
	private List tempLists;
	
	@Test
	public void getPersonValues(){					// 通過Person類中 @ConfigurationProperties註解類匹配屬性名來獲取值
		System.out.println(person1.getName());
		System.out.println(person1.getAge());
		System.out.println(person1.getBirth());
		System.out.println(person1.getMaps());
		System.out.println(person1.getLists());
		System.out.println(tempLists);
	}
	
	@Autowired
	ApplicationContext ioc;
	
	@Test
	public void testContainsHelloService() {
		boolean res = ioc.containsBean("helloService");
		System.out.println(res);
	}
	
	
}

 

注意:

Application類和Test類所在的包,必須處在其他業務邏輯包的上層,才可以在啟動時順利注入其他類和配置。