spring boot使用application.properties默认了很多配置。但需要自己添加一些配置的时候,我们应该怎么做呢。
例如在application.properties配置文件中加入如下配置:
person.name=zhangsaninapplication
person.gender=maninapplication
那么如何在应用程序中进行读取呢?
首先定义配置读取实体类:
com.hpit.sb.properties.MyConfig
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* TODO定义读取自定义配置类
*
* @author郑江山
*
*/
@ConfigurationProperties(prefix = "person") // 读取系统配置文件中的preson开头的所有配置,并自动封装到实体类中
public class MyConfig {
private String name;
private String gender;
public MyConfig() {
}
public MyConfig(String name, String gender) {
super();
this.name = name;
this.gender = gender;
}
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
public String getGender() {
returngender;
}
publicvoid setGender(String gender) {
this.gender = gender;
}
}
添加@ConfigurationProperties注解用来读取application.properties配置文件中以person开头的所有配置。
2.在spring boot入口类加入:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
importorg.springframework.context.annotation.Bean;
import com.hpit.sb.properties.MyConfig;
importcom.hpit.sb.servlet.MyServlet1;
/**
*
*
* 大家也许会看到有些demo使用了3个注解:@Configuration;
*
* @EnableAutoConfiguration
* @ComponentScan其实:@SpringBootApplication申明让spring boot自动给程序进行必要的配置,
* 等价于以默认属性使用@Configuration,
* @EnableAutoConfiguration和@ComponentScan 所以大家不要被一些文档误导了,让自己很迷茫了,希望本文章对您有所启发;
*
* @author郑江山
*/
@SpringBootApplication
@ServletComponentScan// 方式二:添加servlet注册扫描,将自动注册添加了@WebServlet的类为serlvet
@EnableConfigurationProperties(MyConfig.class) // 配置加载读取自定义配置类
public class App {
/**
* 方式一:注册Servlet.不需要添加注解:@ServletComponentScan 这种方式已经在springboot中废弃
*
* @return
*/
/*
* @Bean public ServletRegistrationBean regMyServlet1() { return new
* ServletRegistrationBean(new MyServlet1(), "/myServlet/*"); }
*/
publicstaticvoid main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
如何是定义其他配置文件中,需要将实体类改写为: