我们学习过将配置信息,通过@Value()的方法注入到对象的变量。这是由于对象是由spring来托管的。那么非spring如果,我们需要在静态方法中,使用配置文件中的值,又该怎么做呢?
传统的错误作法
application.properties
?
1
|
spring.redis.host=test
|
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Component
public class RedisServiceImpl implements RedisService {
...
@Value ( "${spring.redis.host}" )
static public String host;
@Value ( "${spring.redis.port}" )
static public Integer port;
...
static public JedisPool getJedisPool() {
if (RedisServiceImpl.host == null ) {
logger.info( "host 未注入" );
}
}
|
控制台打印为: "host 未注入
正确的方法
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
@Component
public class RedisServiceImpl implements RedisService {
...
static public String host;
static public Integer port;
@Value ( "${spring.redis.host}" )
public void setHost(String host) {
RedisServiceImpl.host = host;
}
@Value ( "${spring.redis.port}" )
public void setPort(Integer port) {
RedisServiceImpl.port = port;
}
...
static public JedisPool getJedisPool() {
if (RedisServiceImpl.host == null ) {
logger.info( "host 未注入" );
} else {
logger.info( "host 值为" + RedisServiceImpl.host);
}
}
|
控制台正确的打印了注入的值。
原因猜想
spring
进行组件扫描,遇到@Component
时,初始化对象 RedisServiceImpl
, 初始化过程中,扫描到@Value
注解,将值注入给方法。
接着,方法将值传给了RedisServiceImpl
类,故RedisServiceImpl
有值 — 正解。
如果将@Value(),
直接加到静态私有变量上,则在初始化对象时,由于静态私有变量属于类,所以spring未对类进行操作 — 错误。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:https://segmentfault.com/a/1190000015262017
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 73
-
2025-05-29 17
-
2025-05-25 60
-
2025-05-25 41
-
2025-05-27 30
热门评论