Springboot可以通过application.properties和application.yml读取配置文件,如果需要读取自定义配置文件信息,可以通过以下方法
一、通过@PropertySource加载自定义配置文件
1、在springboot项目resources文件夹下新建student.properties
student.number=1001
student.name=张三
student.classes=计算机
新建Student类:
@Component:将当前bean注入到容器中
@ConfigurationProperties(prefix = "student"):从配置文件中找student开头的
若是自定义的properties文件则需要:@PropertySource注解定义配置文件路径
@Component
@PropertySource({"classpath:student.properties"})
@ConfigurationProperties(prefix = "student")
public class Student {
private Long number;
private String name;
private String classes;
//省略get set toString
}
测试类:运行ok
@SpringBootTest
class StudentApplicationTests {
@Autowired
Student student;
@Test
void contextLoads() {
System.out.println(student);
}
}
打印:
Student{number=1001, name='张三', classes='计算机'}
二、通过@ImportResource注入xml配置文件
1、刚才的Student类去除所有注解
//@Component
//@PropertySource({"classpath:student.properties"})
//@ConfigurationProperties(prefix = "student")
public class Student {
private Long number;
private String name;
private String classes;
//省略get set toString
}
2、resources下新建student.xml文件进行属性设置
3、启动类中新加@ImportResource
@ImportResource({"classpath:student.xml"})
@SpringBootApplication
public class PropertiesApplication {
public static void main(String[] args) {
SpringApplication.run(PropertiesApplication.class, args);
}
}
运行测试打印出student:
测试类:运行ok
@SpringBootTest
class StudentApplicationTests {
@Autowired
Student student;
@Test
void contextLoads() {
System.out.println(student);
}
}
打印:
Student{number=1002, name='李四', classes='经济学'}
三、使用@Configuration和@Bean添加组件
1、刚才的Student类去除所有注解
2、新建StudentConfig配置类
//等同于spring.xml配置,注入到容器
@Configuration
public class StudentConfig {
//给bean id student 设置属性
@Bean
public Student student() {
Student student = new Student();
student.setNumber((long) 1003);
student.setName("王五");
student.setClasses("师范");
return student;
}
}
运行测试打印出student:
测试类:运行ok
@SpringBootTest
class StudentApplicationTests {
@Autowired
Student student;
@Test
void contextLoads() {
System.out.println(student);
}
}
打印:
Student{number=1003, name='王五', classes='师范'}