1 @ConfigurationProperties说明
在编写项目代码时,我们要求更灵活的配置,更好的模块化整合。在 Spring Boot 项目中,为满足以上要求,我们将大量的参数配置在 application.properties 或 application.yml 文件中,通过 @ConfigurationProperties 注解,我们可以方便的获取这些参数值
2 使用@ConfigurationProperties
ConfigurationPropertiesTest.java
/**
* @desc: @ConfigurationProperties
* @author: YanMingXin
* @create: 2021/7/27-17:36
**/
@ConfigurationProperties(prefix = "student")
@Component
public class ConfigurationPropertiesTest {
private String name;
private String age;
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;
}
}
SpringUtil.java
/**
* @desc: SpringUtil
* @author: YanMingXin
* @create: 2021/7/27-17:55
**/
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
application.properties
student.name=zs
student.age=23
测试:
@Test
void contextLoads() {
ConfigurationPropertiesTest bean = (ConfigurationPropertiesTest) SpringUtil.getBean("configurationPropertiesTest");
System.out.println(bean.getAge());
}
输出:
23