全局配置文件 application.properties或yaml
例如
一,全局配置文件
1,properties文件格式:
server.port = 8081
server.servlet.context-path=/hello
person.age = 11
person.name = lisa
person.family = father,mother
2,yaml文件格式:
server:
port: 8081
servlet:
context-path: hello
person:
age: 11
name: lisa
family: [father,mother]
3,注解:@component //生成当前类的实例对象存到IOC容器中
除了@Component外还有@Controller,@Service,@Repository,@Configuration
作用是将自定义类作为Spring容器的组件,让Springboot可以自动扫描到该组件
@ConfigurationProperties(prefix = “person”)
//将配置文件的前缀为person的每隔属性的值映射到当前类的变量上
@ConfigurationProperties直接用来快速配置文件中的自定义属性值批量注入Bean对象的对应属性中
注意要有get set 和 toString
要有提示在配置类写spring-boot-configuration-processor
修改了要重新运行
注意:访问不是在项目启动类测试,而是要在test类测试,或者新建一个类,用web方式访问
记得在实例类时要加@Autowired
4,自定义的配置类
注解:@Configuration注解表示当前类是自定义的配置类,作为Bean组件添加到Spring容器中,相当于@Component
@PropertySource(“classpath:test.properties”)指定了自定义文件的位置和名称
@ConfigurationProperties(prefix=“test”)和默认同
@ConfigurationProperties(MyProperties.class)开启配置类的属性注入功能配合上一个注解使用的,如果是使用@Component而不是
@Configuration可以省略
使用@Configuration自定义配置类
使用@Bean注解方法,将返回值对象作为组件添加到Spring容器中,类似于xml文件中的<Bean>标签
如 @Bean
public Person myPerson(){
return new Person();
}其中将该组件的id默认是方法名myPerson