SpringBoot 自定义属性配置
有以下几种方式:
第一种方式:
在application.yml配置文件中定义属性:
learn:
userName: root
password: 123456
java代码中应用:采用@Value注解获取自定义属性
@Value("${learn.userName}")
private String username;
@Value("${learn.password}")
private String password;
第二种方式
在application.yml配置文件中定义属性:
learn2:
userName: root
password: 123456
创建配置类
/**
* application.yml 文件自定义属性
* 通过 @ConfigurationProperties 方式引入配置文件
* 需要配置get set方法,构造方法
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Component
@ConfigurationProperties(prefix = "learn2")
public class TestEntity {
private String userName;//跟配置文件中的属性需要一致
private String password;
}
在代码中引用:
@Autowired
TestEntity entity;
log.info("entity.userName={}",entity.getUserName());
log.info("entity.password={}",entity.getPassword());
第三种方式
custom.yml自定义配置文件
learn3:
hobby:
hobby1: 篮球11sssss
hobby2: 读书dcvvvg123
/**
* 引入单独的配置文件custom.yml 自定义属性
* getter、setter 方法注入及获取配置
*
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Component
@PropertySource(value = {"classpath:custom.yml"},encoding = "UTF-8")
@ConfigurationProperties(prefix = "learn3.hobby")
public class TestProperties {
@Value("${hobby1}")
private String hobby1;
@Value("${hobby2}")
private String hobby2;
}
在代码中引用:
@Autowired
TestProperties testProperties;
log.info("testProperties.hobby1={}",testProperties.getHobby1());
log.info("testProperties.hobby2={}",testProperties.getHobby2());
第四种方式
custom4.yml自定义配置文件
learn4:
are:
are1: 上海bnh234
are2: 赣州hju789
自定义配置类:
/**
*引入单独的配置文件 自定义属性
*
*/
@Configuration
@PropertySource(value = {"classpath:custom4.yml"},encoding = "UTF-8")
@ConfigurationProperties(prefix = "learn4.are")
public class Test4Properties {
@Value("${are1}")
private String are1;
@Value("${are2}")
private String are2;
public Map<String,Object> map = new HashMap<>();
@Bean
public Map<String,Object> getMap(){
map.put("are1",are1);
map.put("are2",are2);
return map;
}
}
在代码中引用:
@Autowired
Test4Properties test4Properties;
log.info("test4Properties.are1={}",test4Properties.getMap().get("are1"));
log.info("test4Properties.are2={}",test4Properties.getMap().get("are2"));
备注:
引入测试依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
@Slf4j
@RunWith(SpringRunner.class) //固定写法
@SpringBootTest(classes = LearnCustomPropertiesApplication.class) //自定义
public class LearnCustomPropertiesApplicationTests {
。。。。
}
网友评论