java properties null_遇到问题---java---@value注解为null

Spring 3支持@value注解的方式获取properties文件中的配置值,大简化了读取配置文件的代码。

在xml文件中配置properties文件

例如

cas.authn.mongo.collection.name=crmUser

cas.authn.mongo.db.host=mongodb://192.168.30.249:27017/testCrm

cas.authn.mongo.attributes=username,password,phone,crmRoles

cas.authn.mongo.username.attribute=username

cas.authn.mongo.password.attribute=password

525e54695014b01359050db96cb61d3a.png

在任意xml中加入

在java文件中即可使用@value注解获取配置文件的值

@Repository("personMongoDB")

public class PersonMongoDB {

private static final Logger LOGGER = LoggerFactory

.getLogger(PersonMongoDB.class);

@Value("${cas.authn.mongo.collection.name:users}")

private String collectionName;

@Value("${cas.authn.mongo.db.name:cas}")

private String databaseName;

@Value("${cas.authn.mongo.db.host:}")

private String mongoHostUri;

@Value("${cas.authn.mongo.attributes:}")

private String attributes;

@Value("${cas.authn.mongo.username.attribute:username}")

private String usernameAttribute;

@Value("${cas.authn.mongo.password.attribute:password}")

private String passwordAttribute;

public void setMongoHostUri(final String mongoHostUri) {

this.mongoHostUri = mongoHostUri;

}

public void setCollectionName(final String collectionName) {

this.collectionName = collectionName;

}

public void setDatabaseName(final String databaseName) {

this.databaseName = databaseName;

}

public void setAttributes(final String attributes) {

this.attributes = attributes;

}

public void setUsernameAttribute(final String usernameAttribute) {

this.usernameAttribute = usernameAttribute;

}

public void setPasswordAttribute(final String passwordAttribute) {

this.passwordAttribute = passwordAttribute;

}

但是有可能@value注解的属性为null值。这种有可能是缺乏第三个步骤的原因。

确保使用@value的类已经注册为bean或者被spring扫描到

使用@value的类必须注册为spring的容器,所以需要注册为bean。

所以这里需要加上

如果不注册为bean,使用spring来自动扫描也是可以的。

一般都是交给spring管理,controller 全部交给springMVC 去扫描的,spring 配置文件里把注解扫描时没有扫描controller,所有会取不到值。

context:component-scan 扫描多个包 

base-package这里扫描需要覆盖PersonMongoDB所在的路径。

被调用的类也必须选择注解的方式

如果前面三个步骤都做了还是null值,可以考虑这个原因:

原因是如果有注入bean的那个类,在被其他类作为对象引用的话(被调用)。这个被调用的类也必须选择注解的方式,注入到调用他的那个类中,不能用 new出来做对象,new出来的对象再注入其他bean就会 发生获取不到的现象。所以要被调用的javabean,都需要@service,交给Spring去管理才可以,这样他就默认注入了。

也就是 例如我上面的PersonMongoDB 在被使用时是不能

new  PersonMongoDB()来使用的,这样注解的属性不会进去。

只能用过注解来使用 PersonMongoDB。

所以我在配置文件中使用到它的bean里配置了PersonMongoDB。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值