application.properties配置文件部分配置
这里简单使用application.properties配置文件部分配置举例,配置如下:
profile.name= test
profile.age= 18
@Value读取一个配置项
@SpringBootApplication
public class TestApplication implements InitializingBean {
@Value("${profile.name}")
private String name;
public static void main(String[] args) {
SpringApplication.run(TestApplication .class, args);
}
@Override
public void afterPropertiesSet() throws Exception {
// My Profile Name:test
System.out.println("My Profile Name:" + name);
}
}
@ConfigurationProperties读取一组配置项
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "profile")
@Data
public class Profile {
private String name;
private String age;
}
@SpringBootApplication
public class TestApplication implements InitializingBean {
@Autowired
private Profile profile;
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Profile Object:" + profile.getName());
System.out.println("Profile Object:" + profile.getAge());
}
}
@PropertySource 读取配置文件
@SpringBootApplication
// 指定读取application.properties配置文件
@PropertySource("classpath:application.properties")
public class TestApplication implements InitializingBean {
// 读取一个配置项,配置文件所属为application.properties配置文件
@Value("${profile.name}")
private String name;
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Name:" + name);
}
}
另外还可以使用 Environment 读取配置文件,Environment 是 Spring Core 中的一个用于读取配置文件的类,将此类使用 @Autowired 注入到类中就可以使用它的 getProperty 方法来获取某个配置项的值;还可以通过原生 Properties 对象来读取配置文件,在开发中常用的还是我上面进行举例的三种,这里列举的两种方式作为了解就好