上例中使用@Value注入每个配置在实际项目中会显得格外麻烦,因为我们的配置通常会是许多个,若使用上例的方式则要使用@Value注入很多次。
Spring Boot还提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联,从而实现类型安全的配置。
添加配置,即在application.properties上添加:
author.name = shrimp king
author.age = 99
当然,我们也可以新建一个properties文件,这就需要我们在@ConfigurationProperties的属性locations里指定properties的位置,且需要在类上配置。
我这里建立了mytest.properties
server.port=8089
server.context-path=/t1
author.name = shrimp king
author.age = 99
类型安全的Bean,代码如下:
package com.shrimpking.Test2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/1/7 17:33
*/
@Component
@ConfigurationProperties(prefix = "author",locations = {"classpath:mytest.properties"})
public class AuthorSettings
{
private String name;
private Long age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Long getAge()
{
return age;
}
public void setAge(Long age)
{
this.age = age;
}
}
通过@ConfigurationProperties加载properties文件内的配置,通过prefix属性指定properties的配置的前缀,通过locations指定properties文件的位置,例如:@ConfigurationProperties(prefix = "author",locations = {"classpath:mytest.properties"})
package com.shrimpking.Test2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/1/7 17:31
*/
@RestController
public class Test2Controller
{
@Autowired
private AuthorSettings authorSettings;
@RequestMapping(value = "/index2",method = RequestMethod.GET)
public String index2(){
return "author name is: " + authorSettings.getName()
+ " and author age is: " + authorSettings.getAge();
}
}
可以用@Autowired直接注入该配置。