微服务SpringBoot笔记(2)

在src/main/resources目录下有个 application.propertires的配置文件,这个文件有什么用呢,我们该文件写如下语句:

spring.application.name=/quickstart
server.context-path=/qs

server.port=8082

custom.group = 12345
custom.team = 67890

注:该文件的注释方式是 #

我们可以设置应用程序的名字以及路径,Tomcat的端口号,还可以设置相关值,这些值可以在类中读取,当然 在application.propertires文件中可以设置很多属性,以后再了解。

加了程序路径后,那么在页面访问时就要加上路径了,例如:

下面创建类读取custom.group和custom.team的值。

package com.cc.springboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;


@Configuration  
public class AppConfig {
	
	@Value("${custom.group}")
	private String customGroup;
	
	@Autowired
	private Environment environment;
	
	public void output() {
		System.out.println("通过@Value读取的配置值是" + customGroup);
		System.out.println("通过Environment获取" + environment.getProperty("custom.team"));
	}
}

@Configuration,这个注解有什么用呢,塔可以让spring识别这个类,代替了之前的xml文件的形式。

读取配置文件里的值,我们有两种方式

(1)用@Value注解,直接将值赋给类的属性

 (2)通过@Autowired 修饰Environment对象来获取,然后调用getProperty()方法,注意必须是                     org.springframework.core.env.Environment

我们在main函数调用该类:

package com.cc.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Springboot01Application {

	public static void main(String[] args) {
		ConfigurableApplicationContext ctx = SpringApplication.run(Springboot01Application.class, args);
		AppConfig appCfg = ctx.getBean(AppConfig.class);
		appCfg.output();
	}

}

启动程序,输出如下:

猜你喜欢

转载自blog.csdn.net/yao_hou/article/details/86585413