SpringBoot 使用注解将配置文件自动映射到属性和实体类
2018-07-05 18:42
956 查看
1. 属性单独映射
1. Controller上面配置
@PropertySource({"classpath:application.properties"})
2. 对要配置的属性添加注解
@Value("${web.file.path}") private String filePath;
3. 接口测试
@GetMapping("/test/property-source") public Object testPropertySource() { System.out.print("配置注入打印,文件路径为:" + filePath); return filePath; }
2. 实体类配置文件(使用配置实体类)
1. 创建配置
application.properties 文件中添加一下内容# 测试实体类注入 test.name = shadowolf test.domain = www.shadowolf.cn
2. 创建一个实体类 ServiceSettings.java
两个属性 name 和 domain添加两个属性的get和set方法
3. 给类添加注解
共有三个注解:@Component、@PropertySource、@ConfigurationProperties@ConfigurationProperties 注解可以设置 key 的前缀
@ConfigurationProperties(prefix = "test")
详细代码
// 服务器配置
@Component
@PropertySource({"classpath:application.properties"})// @ConfigurationProperties
@ConfigurationProperties(prefix = "test")public class ServiceSettings {}
4. 添加@Value注解
@Value("${name}") private String name; @Value("${domain}") private String domain;
如果此处配置文件中的key与属性名意义对应,可以不加@Value注解,假如不一致,那么就需要加@Value注解进行映射
5. 使用配置实体类
用到的地方进行注入@Autowired private ServiceSettings serviceSettings; @GetMapping("/test/test-properties") public Object testProperties() { System.out.println("serviceSettings: " + serviceSettings); return serviceSettings; }
相关文章推荐
- Spring Boot 使用@ConfigurationProperties注解获取配置文件中的值
- spring boot:使用@ConfigurationProperties注解加载配置文件
- [原创]java WEB学习笔记99:Spring学习---Spring Bean配置:自动装配,配置bean之间的关系(继承/依赖),bean的作用域(singleton,prototype,web环境作用域),使用外部属性文件
- Spring4深入理解IOC&DI02----Bean配置--自动装配、bean之间的继承与依赖、使用外部属性文件
- spring boot 使用@ConfigurationPropertiesu将配置自动封装成实体类
- 【spring boot】使用@Value映射properties文件属性
- spring-自动加载配置文件\使用属性文件注入
- spring-自动加载配置文件\使用属性文件注入
- Spring中使用事务搭建转账环境方法二 相对简便的注解方法 ——配置文件注入对象属性需要setter方法 注解方法,不需要生成setter方法
- JPA项目使用myeclipse创建带注解的model实体类&web工程使用MyEclipse自动生成hibernate映射文件和实体类
- SpringBoot内部配置:“application.properties配置”和”使用XML配置”,读取属性文件中的内容,日志配置,Profile配置(学习:SpringBoot实战)
- Spring 3.0 学习-DI 依赖注入_创建Spring 配置-使用一个或多个XML 文件作为配置文件,使用自动注入(byName),在代码中使用注解代替自动注入,使用自动扫描代替xml中bea
- spring-自动加载配置文件\使用属性文件注入
- Spring中使用事务搭建转账环境方法二 相对简便的注解方法 ——配置文件注入对象属性需要setter方法 注解方法,不需要生成setter方法
- 使用mybatis-generator自动生成实体类,接口实现类和Mapper映射配置文件
- spring-boot使用注解获取配置文件中的值
- 关于使用注解的Spring配置文件的配置<context:annotation-config/>&&<context:component-scan base-package=”XX.XX”/>
- 使用Spring的mappingDirectoryLocations来配置Hibernate映射文件
- Spring AMQP实例 以及Spring 配置文件动态注入属性使用实战
- spring与jpa整合 简化persistence.xml配置文件 使用属性文件 数据源dbcp访问数据库