一、首先创建一个springboot项目
选择一个web
二、创建一个类
public class Student {
private String name;
private Integer age;
private Boolean monitor; //是否是班长
private Map<String,Object> maps;
private List<String> lists;
private Dog dog; //引入一个对象
}
public class Dog {
private String name;
private String color;
}
然后在pom文件里面引入映射提示的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
然后在Student类上加上两个注解
@Component //表示猪肉容器 @ConfigurationProperties(prefix = "student") //表示要影视的配置文件
yml的配置文件
server:
port: 8081
student:
name: 张三
age: 16
monitor: true
maps: {k1: v1,k2: 哈哈}
lists:
- cat
- pig
- hhhh
dog:
name: 小猪
color: 灰色
然后在测试类里面进行测试
@SpringBootTest
class SpringBoot02HelloworldQuickApplicationTests {
@Autowired
Student student;
@Test
void students() {
System.out.println("打印"+student);
}
}
查看结果,打印成功
三、对配置文件进行修改
如上,你会发现,如果我要打印输出很多配置文件,但是我不可能都写到yml配置文件里面去
所以我重新创建一个配置文件,先这些注释掉
然后创建一个student.properties文件
这时你会发现这样的配置文件不行,那么这时候你就得先吧yml文件转换成.properties这个配置文件,可能有小伙伴不会转换,看操作
先下载一个插件:File--->Settings--->Plungins--->然后找到Marketplace进行搜索
“Convet YAML and Properties File”这个插件并进行安装,安装完成之后
你右击application.yml你会发现有一个Convet YAML and Properties File的一个按钮,然后点击就行,这时候你会发现你点击完以后,会出现乱码,不要慌,进行设置utf-8就行了
File--->Settings--->Editor--->Code Style-->File Encodin然后讲这些都设置utf-8就行了,然后点击应用就行了最终的配置文件是
这样也能打印成功,如果你的有中文,可能会乱码,这样你先吧那个新创建的配置文件给删除,然后重新创建,这样就可以解决乱码的的问题了
四、以前是直接创建Spring的配置文件的,现在不用创建了,可以直接写配置文件了,
操作:首先我们创建一个配置类
创建完成之后我们要在配置类上添加注解
@Configuration
public class HelloConfig {
//HelloService(自定义)这个是为了测试能不能进行注入的一个类
@Bean
public HelloService helloService(){
System.out.println("注入bean");
return new HelloService();
}
}
那么测试:
@Autowired
ApplicationContext api; //ApplicationContext这个要引入import org.springframework.context.ApplicationContext;这个依赖
@Test
public void beanTset(){
boolean b = api.containsBean("helloService"); //helloService这个必须和要注入的名字一样包括大小写
System.out.println("是否成功。。"+b);
}
可以注入成功。,