使用注解读取properties配置文件

1、背景

服务中使用到了redis,需要配置redis连接相关信息

redis.properties(在src.main路径下,和java包同等级的 resources包下)

spring.redis.host=127.0.0.1
spring.redis.password=123456
spring.redis.database=3
spring.redis.port=6379
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=1500
  • 常规的方法可以使用Properties结合InputStream流,或
ResourceBundle resource = ResourceBundle.getBundle("redis");//不需要加.properties后缀 
String key = resource.getString("host");
  • 除此外,还可以使用注解的方式,读取配置信息

2、注解方式

2.1 @PropertySource 、 @ConfigurationProperties
2.2 读取properties中全部字段值@ConfigurationProperties

1、配置类

@Configuration 
@PropertySource("classpath:redis.properties") 
public class RedisConfig

	@Bean
	@ConfigurationProperties(prefix = "spring.redis")
	public RedisClient redisClient(){
		return new RedisClient( );
    }
}

补充:
这里@Configuration + @Bean,则redisClientConfig()无论调用多少次,即使每次调用方法,内部都是new新的RedisClient,但是这里bean对象不是普通的对象,是cglib加强过的对象,是单例的。保证无论调用多少次redisClientConfig(),不论其内部是new RedisClient(),都是获取相同的RedisClient对象

@Service
public class RedisGateway 

	@Autowired 
	private RedisClient redisClient; 

	public void getXxx( ) { 
        redisClient.setNx();
    }
}
2.3 读取properties中部分字段值:@value(“${自定义key}”)

如果只想获取redis.properties中spring.redis.host字段的值:127.0.0.1

@Component 
@Configuration
@PropertySource("classpath:redis.properties") 
public class RedisGateway { 
    
	@Value("${spring.redis.host}") 
	private String ipAdress; 
    
    public void getIpAddress() {
		String result =ipAdress;
	} 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,您可以使用注解读取配置文件中的数据。使用注解的好处是可以将数据注入到类属性中,从而方便地在代码中使用这些数据。 以下是一个简单的例子,演示如何使用注解读取配置文件中的数据: 首先,创建一个配置文件`config.properties`,并添加以下内容: ``` database=mysql dbuser=root dbpassword=123456 ``` 然后,创建一个类`Config.java`,并添加以下代码: ```java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import java.util.Properties; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface ConfigProperty { String value() default ""; } public class Config { @ConfigProperty("database") private String database; @ConfigProperty("dbuser") private String dbUser; @ConfigProperty("dbpassword") private String dbPassword; public Config() { readConfig(); } private void readConfig() { Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream("config.properties"); prop.load(input); for (Field field : this.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(ConfigProperty.class)) { ConfigProperty annotation = field.getAnnotation(ConfigProperty.class); String propertyName = annotation.value().isEmpty() ? field.getName() : annotation.value(); String propertyValue = prop.getProperty(propertyName); field.setAccessible(true); field.set(this, propertyValue); } } } catch (IOException | IllegalAccessException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } public String getDatabase() { return database; } public String getDbUser() { return dbUser; } public String getDbPassword() { return dbPassword; } } ``` 在这个例子中,我们定义了一个注解`@ConfigProperty`,它可以用于类属性上。注解有一个属性`value`,可以用来指定配置文件中的属性名。如果未指定,则默认使用属性名作为配置文件中的属性名。 我们还定义了一个`readConfig()`方法,用于读取配置文件中的数据并将其注入到类属性中。在这个方法中,我们使用`Properties`类来加载配置文件。然后,我们遍历类中的所有属性,如果属性上有`@ConfigProperty`注解,则使用反射机制将属性设置为配置文件中的值。 最后,我们可以创建一个`Main.java`类,来测试`Config.java`类: ```java public class Main { public static void main(String[] args) { Config config = new Config(); System.out.println("Database: " + config.getDatabase()); System.out.println("DB User: " + config.getDbUser()); System.out.println("DB Password: " + config.getDbPassword()); } } ``` 在这个例子中,我们创建了一个`Config`对象,并打印出从配置文件读取的数据库信息。 当我们运行`Main.java`时,输出如下: ``` Database: mysql DB User: root DB Password: 123456 ``` 这表明我们已成功从配置文件读取了数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值