SPRing 3支持@value注解的方式获取properties文件中的配置值,大简化了读取配置文件的代码。
例如
cas.authn.mongo.collection.name=crmUser
cas.authn.mongo.db.host=mongodb://192.168.30.249:27017/testCrmcas.authn.mongo.attributes=username,passWord,phone,crmRolescas.authn.mongo.username.attribute=usernamecas.authn.mongo.password.attribute=password
在任意xml中加入
<util:properties id="casproperties" location="${cas.properties.config.location:/WEB-INF/cas.properties}"/> <context:property-placeholder properties-ref="casProperties"/>
@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的类必须注册为spring的容器,所以需要注册为bean。
所以这里需要加上
<bean id="personMongoDB" class="self.PersonMongoDB" />
如果不注册为bean,使用spring来自动扫描也是可以的。
一般都是交给spring管理,controller 全部交给springMVC 去扫描的,spring 配置文件里把注解扫描时没有扫描controller,所有会取不到值。
context:component-scan 扫描多个包 <context:component-scan base-package="com.aaa.service,com.aaa.util"/>
base-package这里扫描需要覆盖PersonMongoDB所在的路径。
如果前面三个步骤都做了还是null值,可以考虑这个原因:
原因是如果有注入bean的那个类,在被其他类作为对象引用的话(被调用)。这个被调用的类也必须选择注解的方式,注入到调用他的那个类中,不能用 new出来做对象,new出来的对象再注入其他bean就会 发生获取不到的现象。所以要被调用的javabean,都需要@service,交给Spring去管理才可以,这样他就默认注入了。
也就是 例如我上面的PersonMongoDB 在被使用时是不能
new PersonMongoDB()来使用的,这样注解的属性不会进去。
只能用过注解来使用 PersonMongoDB。
所以我在配置文件中使用到它的bean里配置了PersonMongoDB。
<bean id="attributeRepository" p:backingMap-ref="attrRepoBackingMap" p:personMongoDB-ref="personMongoDB" class="self.MongoDBPersonAttributeDao" /> <bean id="personMongoDB" class="self.PersonMongoDB" />
新闻热点
疑难解答