自定义自动配置类:
1.pom.xml添加自定义配置文依赖
2.创建一个自定义配置类
3.创建一个config类用注解激活自定义配置类,并@ConditionalOnMissingBean检查容器中是否有此Bean
4.在application.properties配置自定义配置类的属性
5.访问路径,日志信息输出配置属性值
6.测试结果
在我们了解此配置之后对springboot的源码了解有非常大的提升。
1.pom.xml添加此依赖:
<!--自定义配置文件必须由此依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.创建一个自己的自定义配置类
/**
* @Author: gxm
* @Date: Created by 2019/11/16 22:52
* @Description: 自己的属性配置类。在application.properties 配置的路径就是 gxm.类属性名
* 这个属性配置类,需要创建一个spring配置类来激活属性配置类
*
* 注意:自定义配置文件的时候一定需要在pom.xml 有个自定义配置的依赖。
*/
@ConfigurationProperties(prefix = "gxm")
public class MyGxmProperties {
private String name;
private String age;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
3.创建一个config类用注解激活自定义配置类
/**
* @Author: gxm
* @Date: Created by 2019/11/16 22:57
* @Description:
* @EnableConfigurationProperties 激活自定义属性扫描文件
* 多个自定义配置文件以逗号隔开配置
* @Configuration 注解表明是一个Spring 配置类
*/
@EnableConfigurationProperties({
MyGxmProperties.class //激活自定义属性扫描文件(MyGxmProperties)
})
@Configuration
public class GxmPropertiesConfig {
/***
* 特别注意:::这里的注入容器中的Bean中的方法名需要注入容器的配置类的第一个字母小写。
* @return
*/
@Bean
@ConditionalOnMissingBean //检查容器中是否有此Bean。若有用容器中的,否则此Bean生效。
public MyGxmProperties myGxmProperties(){
MyGxmProperties myGxmProperties = new MyGxmProperties();
myGxmProperties.setName("李四");
myGxmProperties.setAge("22");
myGxmProperties.setGender("女");
return myGxmProperties;
}
}
4.在application.properties配置自定义配置类的属性
#配置项目的访问根路径
server.servlet.context-path=/crud
gxm.name=张三
gxm.age=22
gxm.gender=男
5.访问路径,日志信息输出配置属性值
@Controller
public class HelloController {
static final Logger logger = LoggerFactory.getLogger(HelloController.class);
@Autowired
MyGxmProperties myGxmProperties;
@RequestMapping(value = "/gxmhello")
public String hello(){
logger.info("自定义属性测试开始.....");
logger.info("name===" + myGxmProperties.getName());
logger.info("age==="+myGxmProperties.getAge());
logger.info("gender===" + myGxmProperties.getGender());
return "gxmtestpage";
}
}
6.测试结果:
(1).在application.properties自己未配置时结果是:
访问url路径得到日志输出结果:
(2).application.properties开启我们的配置
重启服务再次访问路径日志输出结果: